Ruby compare objects [duplicate]
Pos开发者_如何学Pythonsible Duplicate:
=== vs. == in Ruby
I was wondering what the difference is between the == and the === comparison in Ruby? What is the general definition of when to use which?
'===' is a broader (weaker) notion than the equality '=='. '===' becomes true not only under equality, but also under notions such as, matching a regular expression, being an instance of a class, etc. Despite what sarnold says, I actually do use '===' as a shorthand for 'kind_of?'. Where A is a class,
A === a
can be used as a shorthand of
a.kind_of?(A)
One thing to be careful is that, despite its appearance, it is not commutative. So,
a === A
will not work as intended.
You never actually call ===
yourself. The language calls ===
behind the scenes when you're using case
statements: http://www.skorks.com/2009/08/how-a-ruby-case-statement-works-and-what-you-can-do-with-it/
If you want different behavior for a class in case
statements than the standard Object#===
provides, then you'll need to redefine it. But I've never really looked hard enough to find a reason to replace the standard definition. :)
== is used for equality in conditional statements like if, unless, etc. === is used for determining equality in case statements.
精彩评论