This guide will look at various ways we can reverse a string in the Ruby programming language.
Method 1: Reverse
The simplest way to reverse a string in Ruby is to use the built-in reverse method. A string is an array of characters in sequential order. Hence, we can use the reverse method to get the input string elements in reverse order.
The example above should return “Hello, world!” in reverse:
The reverse method does not affect the original string; it only returns a copy in reverse order.
To affect the original string, we can use the reverse! method.
Method 2: Loop
We can also use a loop to reverse a string. In such a case, we iterate over characters in the string and reapply them to a new string in the reverse order.
Consider the following example:
rev = ''
for i in 1..src.length
rev += src[src.length - i]
NOTE: You can ignore the “puts src[i]” line. Its purpose there is to illustrate how the code works.
You will notice the result is similar to the reverse function.
Method 3: Reverse Word
Suppose you want to reverse a word instead of a single character? In such a scenario, we can split the provided string and reverse each word.
Take a look at the example below:
word = word.split(" ").reverse!.join(" ")
In the example above, we split the sentence into various words (using spaces). We then reverse each word and join them back again.
The resulting output is as shown:
Method 4: Inject
Another method we can use to reverse a string is to use the inject method. It works closely similar to reduces, and many people consider it an alias.
We start by creating an array from the specified string using the chars method:
Once we have the array of characters, we can call the inject method.
The resulting value is the passed string in reverse order.
You can learn more about the reverse string from the following resource.
This guide covers various methods you can implement to reverse a string in Ruby. Feel free to explore more or create your custom functions.