In Ruby, we use the reverse!
method to permanently reverse a string.
Note: The
reverse!
method is different from thereverse
method.reverse
does 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.
str.reverse!
str
: The string we want to permanently reverse.This method returns a new string that is the reverse of the original.
# 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
Lines 2 to 5: We create some strings.
Line 9 to 12: We call the reverse
method on the strings to permanently reverse the strings.
Line 15 to 18: We print the permanently reversed strings to the console.