Topher Fangio
Topher Fangio

Reputation: 20667

Why does MyObject.new.class === MyObject evaluate to false?

I do the following, and it evaluates to false:

MyObject.new.class === MyObject

However,

MyObject.new.class == MyObject

evaluates to true. Can someone with a bit more Ruby background explain this to me, and if it's okay to use == for this purpose?

Upvotes: 2

Views: 102

Answers (1)

Marek Příhoda
Marek Příhoda

Reputation: 11198

In Ruby, === isn't a stricter version of ==, as it is in some other languages.

The === method has several meanings:

Membership:

(1..10) === 5       # => true

Test whether the argument is an instance of the receiver:

p MyObject.new.class === MyObject.new  # true; it's the same as 
p MyObject.new.is_a? MyObject

Regex match:

/\w+/ === "Ruby"

Case statements:

year = 2011

case year
when 1901..2000
  puts 'Second millennium'
when 2001..2999
  puts 'Third millennium'
end

Other meanings, see ri ===

MyObject.new.class == MyObject is just a normal equality test (MyObject is a class object, and MyObject.new.class is the same class object)

Upvotes: 15

Related Questions