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.
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources