Ruby Reverse String

Strings are a fundamental building block in programming, and it is nearly impossible to imagine a functional program that doesn’t use strings.

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.

For example:

str = "Hello, world!"
puts str.reverse

The example above should return “Hello, world!” in reverse:

!dlrow ,olleH

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.

str = "Hello, world!".reverse!
puts str

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:

src = "Hello, world!"
rev = ''
for i in 1..src.length
    puts src[i]
    rev += src[src.length - i]
puts rev

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.

!dlrow ,olleH

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 = "This is a full sentence."
word = word.split(" ").reverse!.join(" ")
puts word

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:

sentence full a is This

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:

"Hello, world!".chars

Once we have the array of characters, we can call the inject method.

puts "Hello, world!".chars.inject {|x, y| y + x}

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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list