Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is "==" in Ruby always value equality?

Sorry if duplicated (I didn't find it)

This is only to confirm that Ruby's operator == performs always an equality comparison. I.e.

a == b

compares a's value against b's value, instead than, like Java, whether they point to the same object in memory (For this latter thing, in Ruby, you should use a.object_id == b.object_id).

Thus, as a consequence it is safe to compare string values with == in Ruby (while it is not safe to do so in Java)

Thanks

Edit:

The question is on the the default == behavior for any Ruby object, as it can mislead Java-C-C++ programmers assuming a==b compares references themselves, not the reference contents.

Anyway, you can check out this code, using strings

one="hello"
two="he"
two << "llo"

if one == two
  puts "surprise: comparing values, not like in Java"
end

if not one.object_id == two.object_id
  puts "obvious: do this to compare references"
end

Edit 2.

So, in Ruby, the comparison

a == b

checks a's and b's values

but, the assignment

a = b

does not copy values, but makes a and b point to the same object !

continuing with the previous code

puts one.object_id
puts two.object_id

puts " and now "

one = two

puts one.object_id
puts two.object_id
like image 676
cibercitizen1 Avatar asked Sep 15 '12 08:09

cibercitizen1


1 Answers

In Ruby, == can be overloaded, so it could do anything the designer of the class you're comparing wants it to do. In that respect, it's very similar to Java's equals() method.

The convention is for == to do value comparison, and most classes follow that convention, String included. So you're right, using == for comparing strings will do the expected thing.

The convention is for equal? to do reference comparison, so your test a.object_id == b.object_id could also be written a.equal?(b). (The equal? method could be defined to do something nonstandard, but then again, so can object_id!)

(Side note: when you find yourself comparing strings in Ruby, you often should have been using symbols instead.)

like image 142
Thomas Avatar answered Sep 24 '22 21:09

Thomas