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
==
and the functionequals
are inverted to what it is expected in C like languages. – Approachable