9

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?

4 Answers 4

8

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.

Sign up to request clarification or add additional context in comments.

3 Comments

seems like they could have chosen better method names for eql? and equal?
CLISP is worse: eq, eql, equal, equalp, and =. There are better named operators like string-equal and tree-equal though.
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?
1

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

Comments

1

== 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.

Comments

0
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.