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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With