Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse vs Reverse! in Ruby when comparing palindrome

Tags:

string

ruby

I know that reverse creates a new string with the characters of the string in reverse and that reverse! mutates (reverses) the current string in place. My question is why, when for example testing for a palindrome, this occurs?:

a = "foobar"
a == a.reverse    # => false
a == a.reverse!   # => true

Is it because it is the same object in memory, therefore == just checks if they have the same memory location?

Thanks!

like image 736
user4616972 Avatar asked Dec 20 '22 06:12

user4616972


2 Answers

The String#reverse! method returns the string it is called on so

a == a.reverse!

is the same as saying

a.reverse!
a == a

and of course a == a is true.

Note that it doesn't matter in the least what reverse! does to the string, what matters to == in o == o.m is what the method (m) returns.

like image 161
mu is too short Avatar answered Jan 08 '23 16:01

mu is too short


a == a.reverse!   # => true

Is because a.reverse! is executed before comparision.

a.reverse! performs internal string reversing. After this operation is done, a became a string, containing raboof. Since String#reverse! returned the result of reversion, the strings (raboof on the left side as soon as a was already changed by call to #reverse!, and raboof on the right side as a result of call to reverse!) are being compared using #eql?, resulting in true.

Hope it helps.

like image 30
Aleksei Matiushkin Avatar answered Jan 08 '23 16:01

Aleksei Matiushkin