Reverse versus reverse! in ruby ​​when comparing palindrome

I know that reverse creates a new line with line characters in reverse order and that reverse! mutates (cancels) the current line in place. My question is why, when, for example, testing for a palindrome, does this happen ?:

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

This is because it is the same object in memory, so == just checks to see if it has the same memory location?

Thank!

+4
source share
4 answers

The method String#reverse!returns the string to which it is called, therefore

a == a.reverse!

is the same as saying

a.reverse!
a == a

and of course a == atrue.

, , reverse! , == o == o.m, (m).

+7
a == a.reverse!   # => true

a.reverse! .

a.reverse! . a , raboof. String#reverse! , (raboof , a #reverse! raboof reverse!) #eql?, true.

, .

+4

object_id, , ! () .

 > a.object_id
 => 64561940 

 > a.reverse.object_id
 => 61943060 

 > a.reverse!.object_id
 => 64561940 
0

String#reverse! a, String#reverse a.

-1
source

All Articles