Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

How to permanently reverse a string in Ruby

okwudili onyejiaku

Overview

In Ruby, we use the reverse! method to permanently reverse a string.

Note: The reverse! method is different from the reverse method. reverse does not permanently modify a string, but reverse! 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 strings
str1 = "this"
str2 = "is"
str3 = "not"
str4 = "reversed"

# reverse strings
# permanently
str1.reverse!
str2.reverse!
str3.reverse!
str4.reverse!

# print strings
puts str1
puts str2
puts str3
puts str4
Reverse a String Permanently in Ruby

Explanation

  • 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.

RELATED TAGS

ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring