How to permanently reverse a string in Ruby
Overview
In Ruby, we use the reverse! method to permanently reverse a string.
Note: The
reverse!method is different from thereversemethod.reversedoes not permanently modify a string, butreverse!does.
When we call the reverse! method on a string, the original string is modified and reversed. This means the characters in the string are reversed.
Syntax
str.reverse!
Parameters
str: The string we want to permanently reverse.
Return value
This method returns a new string that is the reverse of the original.
Example
# create stringsstr1 = "this"str2 = "is"str3 = "not"str4 = "reversed"# reverse strings# permanentlystr1.reverse!str2.reverse!str3.reverse!str4.reverse!# print stringsputs str1puts str2puts str3puts str4
Explanation
-
Lines 2 to 5: We create some strings.
-
Line 9 to 12: We call the
reversemethod on the strings to permanently reverse the strings. -
Line 15 to 18: We print the permanently reversed strings to the console.