tags:

views:

145

answers:

4

In Java, == is the strongest kind of equality (pointer equality): a == b always implies a.equals(b). However, in Ruby, == is weaker than .equals?:

ruby-1.9.2-rc2 > 17 == 17.0
 => true 
ruby-1.9.2-rc2 > 17.equal?(17.0)
 => false

So, where can I learn more about ==? What kind of checks should I expect when I compare two objects with it?

+6  A: 

briefly this is what you need to know:

The == comparison checks whether two values are equal

eql? checks if two values are equal and of the same type

equal? checks if two things are one and the same object.

A good blog about this is here.

ennuikiller
seems like they could have chosen better method names for eql? and equal?
BC
CLISP is worse: `eq`, `eql`, `equal`, `equalp`, and `=`. There are better named operators like `string-equal` and `tree-equal` though.
CD Sanchez
OK, so I should never use `==` to compare two objects? But even `5` is an object in Ruby... so what is it safe to use `==` to compare? Strings and numbers, certainly. What about arrays? Hashes?
Trevor Burnham
+1  A: 

in reality they're both just methods == means object.==(other_object) equals? means object.equals?(other_object)

In this case, though, equals is used basically for hash lookup comparison i.e. a_hash[1] should not be the same key value pair as a_hash[1.0]

HTH. -r

rogerdpack
A: 
jruby-1.5.0 > 17 ==17
 => true 
jruby-1.5.0 > 17 == 17.0
 => true 
jruby-1.5.0 > 17 === 17.0
 => true 
jruby-1.5.0 > 17.equal?(17.0)
 => false 
jruby-1.5.0 > 17.id
 => 35 
jruby-1.5.0 > (17.0).id
(irb):12 warning: Object#id will be deprecated; use Object#object_id
 => 2114 

Everything in ruby is an object. the object 17 is not the same object as 17.0 and equal? compares objects, not values of objects.

Jed Schneider
+1  A: 

== is, simply, a method. I think it is explained really well here:

Typically, this method is overridden in descendent classes to provide class-specific meaning.

along with an example with Numerics.

There's a pitfall here, though: as == is a method of the left operand, it is not always safe to assume that the result of a==b should be the same as of b==a. Especially in cases when a is a method call, which, in a dynamic language such as Ruby, must not always return values of the same type.

Mladen Jablanović