How to reverse a string in Ruby

Overview

In Ruby, we can use the reverse method to reverse a string. The reverse method reverses the characters of a string and returns a new string with the characters of the original string in reverse order.

Syntax

str.reverse

Parameters

  • str: The string we want to reverse.

Return value

The reverse method returns a new string with the reversed characters of string str.

Example

# create some strings
str1 = "Edpresso"
str2 = "is"
str3 = "awesome!"
# reverse the strings
a = str1.reverse
b = str2.reverse
c = str3.reverse
# print results
puts a
puts b
puts c

Explanation

  • Lines 2 to 4: We create strings and initialize them with values.
  • Lines 7 to 9: We call the reverse method on the strings that we created.
  • Lines 12 to 14: We print the results to the console.

Free Resources