2

Possible 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?

Community
  • 1
  • 1
Mark
  • 7,891
  • 5
  • 27
  • 36
  • 1
    Possible duplicate : http://stackoverflow.com/questions/3422223/vs-in-ruby | None they are not related. One is equality the other is subsumption. – phwd Mar 08 '11 at 08:37
  • @Philippe You are right that would have been my answer but I couldn't find it when I searched for it.. – Mark Mar 08 '11 at 09:20
  • No worries, I found it by luck ... I was testing different ways to search for characters here. – phwd Mar 08 '11 at 09:53
  • This is a duplicate of [What does the “`===`” operator do in Ruby?](http://StackOverflow.Com/q/4467538/#4467823) and [`===` vs. `==` in Ruby](http://StackOverflow.Com/q/3422223/#3422349). – Jörg W Mittag Mar 08 '11 at 18:11

3 Answers3

1

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

sawa
  • 165,429
  • 45
  • 277
  • 381
0

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. :)

sarnold
  • 102,305
  • 22
  • 181
  • 238
0

== is used for equality in conditional statements like if, unless, etc. === is used for determining equality in case statements.

RubyFanatic
  • 2,241
  • 3
  • 22
  • 35