Ruby comparison operators? == vs. ===
Solution 1
==
is used for equality in conditional statements like if
, unless
, etc. ===
is used for determining equality in case
statements.
Solution 2
Both are just methods called on objects. This means that the objects decide which means what. However, there are conventions in Ruby about how these are different. Usually, ==
is stricter than ===
- a === b
will almost always be true if a == b
is. The best place to read about this is http://ruby-doc.org/core/classes/Object.html. Scroll down to the different sections about ==
and ===
. Here are some of the conventions I know about:
-
==
, when applied to plainObject
s, will only be true if one is exactly the same as the other - if they are stored in the same memory location (this is how Ruby works internally). If the arguments are of types other than Object, though, this method will usually be overridden. -
equal?
is just like==
for plainObject
s, but will never be overridden by subclasses. -
===
is used for:- an
is_a?
alternative, backwards.String === 'str'
is true. - matching regexes.
/s[at]r*/ === 'str'
is true.
- an
You can find the specific meaning of ===
for various classes in the documentation for those classes, for example, the Range
version is here (a synonym for include?
): http://ruby-doc.org/core/classes/Range.html#M000691
keruilin
Updated on July 09, 2022Comments
-
keruilin almost 2 years
What's the difference between == and ===? Which one should you use when?
-
CanadianGirl827x almost 14 yearsAs an example, 10 is not equal to 1..20, but it is within that range. So you may want to be able to put the range in your case statement, and have it be selected. Also, note that case statements translate to b===a in statements like
case a when b then true end
-
Telemachus almost 14 yearsA good example of overriding
==
so that it does what you (probably) expect is strings. Compare==
and.equal
for a string literal and a variable pointing at the "same" string. -
Alexis Wilke over 4 yearsWow! The convention in Ruby is reversed compared to JavaScript. Not to confuse anyone...
-
Hiro almost 3 yearsis it just me that feels the right operand being the instance of the left operand is weird? just my lack of experience?