--0016e64c1e00fb468b048e4bd2c1
Content-Type: text/plain; charset=windows-1252
Content-Transfer-Encoding: quoted-printable

On Sat, Aug 21, 2010 at 12:13 AM, Ralph Shnelvar <ralphs / dos32.com> wrote:

>
> Having read your explanation and Dave Thomas' *Programming Ruby 1.9* book
> about the use of === in comparisons in case statements ...
>
> Is it he fact that *case* uses == (two ='s) for non-Class *when's* and uses
> === (three ='s) for *when's* that are Classes?
>
No (I think the following is right, but I'd welcome any corrections) - case
always uses "===", it's just that the meaning of "===" may be different to
"==".

1. case always uses "===" for comparisons; in
  case x
  when y then
the test is y === x

http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html

Common comparison operators, Operator Meaning
== Test for equal value.
=== Used to test equality within a when clause of a case statement.

case operates by comparing the target (the expression after the keyword
case) with each of the comparison expressions after the when keywords. This
test is done using comparison === target. As long as a class defines
meaningful semantics for === (and all the built-in classes do), objects of
that class can be used in case expressions.
...
Ruby classes are instances of class Class, which defines === as a test to
see if the argument is an instance of the class or one of its superclasses.

2. http://www.ruby-doc.org/core/classes/Object.html#M000345
obj === other => true or false
Case Equalityͧor class Object, effectively the same as calling #==, but
typically overridden by descendents to provide meaningful semantics in case
statements.

3. http://www.ruby-doc.org/core/classes/Module.html#M001666
(remembering that Class is a subclass of Module, which I forget when I
initially couldn't find the "===" method in Class)
mod === obj => true or false
Case Equalityͳeturns true if anObject is an instance of mod or one of mod
descendents. Of limited use for modules, but can be used in case statements
to classify objects by class.

Putting that all together, and using the String class as an example:
x = "Karel Capek"
y = "Karel Capek"
p x.object_id #=> 1880688
p y.object_id #=> 1880656, so x & y are different objects
p x == y #=> true
p x === y #=> true, so for String objects "===" is the same as "=="
            # at least for comparing String objects with String objects

p x == String #=> false
p x === String #=> false

p x.class == String #=> true
p String == String #=> true
p x.class === String #=> false
p String === String #=> false

p String == x #=> false
p String === x #=> true; this is what is being used in the case statement
                 # case x; when String then true; else false; end
p String == x.class #=> true
p String === x.class #=> false; same as String === String

--0016e64c1e00fb468b048e4bd2c1--