Hi –
On Sun, 8 Feb 2009, Peter F. wrote:
I love it!
Thank you all for the discourse.
I take Igor’s reference to the Ruby bible as the most authoritative
explanation, which directly indicates that these two are intended to be
equivalent constructs.
Yes, it wasn’t an accident It’s in keeping with the purpose of
===. Basically, === exists so that it can be overridden in classes
(including, but not limited to, Module), and will then exhibit
appropriate behavior for different classes, in case statements.
Thus, for example, Regexp#=== does a match test:
case “abc”
when /abc/ … # /abc/ === “abc”
end
What I like about === most is that it was very elegant looking AND made me
stop to go find out exactly what was going on. Metaprogramming beauty. I
suppose that goes against the grain of some who wish for the code to tell
you clearly what is going on without reference… but how would you know
what <=> or ||= are without reference?
It’s great to learn what it all means, but I wouldn’t necessarily use
some of these intentionally generic methods explicitly. For example, I
would rather do this:
a > b
than this:
(a <=> b) == 1
though of course I want to know what <=> and how to implement my own
<=> methods when necessary. The same holds (even more so in a way,
since <=> at least has consistent semantics) for ===, which is
designed to be overridden and therefore fluid as to its semantics and
meaning.
=== is very cool because it lets you define your own case statements
and have them work based on a method, without your having to call the
method explicitly. And of course if you make up your own meanings for
===, they’re not going to be as obvious as the ones for the built-in
classes (which are few enough that it’s not hard to learn them, even
though they usually have more expressive alternatives). For example,
it’s better to write:
if car.make == make
than
if make === car
which is not indecipherable but which definitely does need to be
deciphered and which even then has a peculiar backwards ring to
it. You might, however, want make objects to be engineered so that
they can case-compare themselves with a car:
case car
when Ford …
etc., but the explicit === can be a bit too much of a “secret
handshake”.
David
–
David A. Black / Ruby Power and Light, LLC
Ruby/Rails consulting & training: http://www.rubypal.com
Coming in 2009: The Well-Grounded Rubyist (The Well-Grounded Rubyist)
http://www.wishsight.com => Independent, social wishlist management!