Reversing Strings in Ruby

September 1, 2014

Let’s say you have a string, the words in the string are in reverse order, you know what even the letters are reversed. Now you need to correct this order, how would you do this? In Ruby, you have a few methods that help you do this that you don’t need to go and loop over your string and fix the order. First let’s do this the hard way by writing all the code to do the looping and ordering.

In this code, we loop over the string in reverse. Each character is appended by accessing it by index. We use a variable ‘i’ as an indexer that is used to evaluate whether we have iterated through the whole length of our string that is incorrect. If there is one thing I have learned about while loops is that they are susceptible to Stack Overflows, I, therefore, tend to stay away from them at all costs.

So how could we write this code without using a loop and with only using the built-in Ruby methods? Enter the reverse method. Reverse returns a new string with the characters from a string in reverse order. So all we need to do to get the same result is call reverse.

Here is the code:

How awesome is that? Pretty cool right. Let’s try something a bit different, what if our words were not in reverse but the sentence was? Let’s take the string ‘reads. sentence this way the is This’, if we were to call reverse it will result in ‘sihT si eht yaw siht ecnetnes .sdaer’. This is obviously totally wrong but fear not, with a few more built-in methods we can correct this.

We go ahead and convert the string to an array called string_array by splitting it by whitespace. Next up we call reverse on string_array that we have just created, doing this puts our words in the correct order in our array. We then call join and pass in whitespace to ensure our string is separated by whitespace and hey presto we have a string that is in the correct order once again.

This was all pretty straight-forward and saved us from using a bunch of loops that will cause headaches at some or other time. Ruby is very expressive and rolls off the tongue like a spoken language. Ruby is fun and full of great features that make a developer’s life easier!


Discussion, links, and tweets

My name is Deon Heyns and I am a developer learning things and documenting them in realtime. Python, Ruby, Scala, .NET, and Groovy are all languages I have written code in. I appeared in the New York Post once. I host my code up at GitHub and Bitbucket so have a look at my code, fork it and send those pull requests.

comments powered by Disqus