String reverse vs reverse! function in Ruby


In Ruby, we have two functions available to us in case we want to reverse the contents of a string. These two functions are reverse and reverse!. While both of them are used to reverse the string, the only difference between them is that the reverse function reverses the string and then generates a new string, whereas the reverse! function reverses a string in place.

reverse Function

The syntax of the reverse function is shown below

new_str = str.reverse

Now, let's first look at an example of the reverse function in Ruby.

Consider the code shown below.

Example 1

# the reverse method in Ruby

str = "TutorialsPoint"

# reversing the string
puts str.reverse

# printing the string
puts "Ruby".reverse

another_str = "India is Beautiful"

# reversing the string
res = another_str.reverse

# printing res
puts res

Output

tnioPslairotuT
ybuR
lufituaeB si aidnI

reverse! function

The syntax of the reverse! function is shown below.

str.reverse

Now let's look at an example of the reverse! function, which is used when we want to reverse a string in place.

Consider the code shown below

Example 2

# the reverse! method in Ruby
str = "TutorialsPoint"

# reversing the string
puts str.reverse!

# printing the string
puts "Ruby".reverse!

another_str = "India is Beautiful"

# reversing the string
another_str.reverse!

# printing another_str
puts another_str

Output

tnioPslairotuT
ybuR
lufituaeB si aidnI

Updated on: 25-Jan-2022

351 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements