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 stringsstr1 = "Edpresso"str2 = "is"str3 = "awesome!"# reverse the stringsa = str1.reverseb = str2.reversec = str3.reverse# print resultsputs aputs bputs c
Explanation
- Lines 2 to 4: We create strings and initialize them with values.
- Lines 7 to 9: We call the
reversemethod on the strings that we created. - Lines 12 to 14: We print the results to the console.