===, include?, =~

G

gwtmp01

I started this post after wondering why
Set doesn't alias :=== to :include?

That led me to look at ===, include?, and =~ for a variety
of classes...

The following table shows the results of executing
pattern.send(method, arg)

Pattern Arg === include? =~
/foo/ "foo" yes fails yes
0..10 5 yes yes Object#=~
["foo"] "foo" Array#== yes Object#=~
Set.new ["foo"] "foo" Set#== yes Object#=~
{"foo", nil} "foo" Hash#== yes Object#=~
String "foo" yes fails Object#=~

yes means that a class specific method definition exists.
Object#=~ always returns false.
Regexp#=== is the same as Regexp#=~
Range#=== is the same as Range#include?

Could ===, include?, and =~ all be unified?
Does anyone have an example where the semantics of these
three methods should be different (other than for
backward compatibility)?

For the "collection" classes (Array, Set, Hash), the ===
method defaults to using the class specific == method.
Does it make sense for === to be semantically equivalent to ==
for "collection" classes? It seems quite reasonable for "value"
classes where case/when/end can be used to look for particular
values but for a collection class a "pattern" match behavior
would seem more useful when the argument is not also a collection.

Collection === element # membership/inclusion test
Collection === Collection # == test

Are there any examples where =~ and === are defined but aren't
aliases for each other?

Minimally, it would seem that Regexp#include? could be aliased
to Regexp#=~ and Class#include? could be aliased to Class#===
This would make collection.include?(element) a "pattern" test
for all the classes I looked at.
 
E

Eric Mahurin

--- [email protected] said:
I started this post after wondering why
Set doesn't alias :=3D=3D=3D to :include?
=20
That led me to look at =3D=3D=3D, include?, and =3D~ for a variety
of classes...

This was the main reason that sent me off making Object#duck to
map method names to the way you need:

http://rcrchive.net/rcr/show/318

My most common usage now is:

set.duck:)=3D=3D=3D,:include?)

It still puzzles me why some people wouldn't want something
like this in the ruby core.

I use this quite a bit with my grammar project. Several of my
basic methods need an argument that responds to =3D=3D=3D.



=09
=09
__________________________________=20
Yahoo! Mail - PC Magazine Editors' Choice 2005=20
http://mail.yahoo.com
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top