William Djaja Tjokroaminata <billtj / y.glue.umd.edu> writes:

> In the previous example by Guy Decoux,
> 
>     module MyModule
>       ....
>       case obj
>       when MyClass    # line NNN
>         ....
>       end
>     end
> 
> in Ruby, line NNN evaluates to "MyClass === obj" and not "obj ===
> MyClass"?

Yes.

> Is there any documentation on this and what is the rationale?


In the PickAxe, looking up '=== (case comparison)' in the index gives
you 3 page numbers, one of which is a table of operators. The other
two both say that this is how it works.

Why is it that way? So you can write:

   case user_input

   when "stop"
      exit

   when /help (.*)/
      do_help($1)

   end

Each comparison can be against a different object type, and use a
different comparison operator (string comparison in the first case,
regexp in the second).

> Again, does this conform to the Priciple of Least Surprise or
> just some additional Ruby tricks that I have to memorize?

In this case there's a logical reason for it...

> Why can't we make "MyClass === obj" and "obj === MyClass" to behave in the
> same way so that we don't have to deal with this extra peculiarity?

Because "fred" === "fred" and /fred/ === "fred", but "fred" does not
=== /fred/. Remember that === is just a method call: in your
particular case you want to override Object#=== to work with
Modules. But what happens if someone else wants it to be the same as
Range#===, or Regexp#===. It's just not a reversible or symmetrical
mapping.


Regards


Dave