logo       

Re: class === class often false?: msg#01162

lang.ruby.general

Subject: Re: class === class often false?

ri Module.=== gives <<EOD

------------------------------------------------------------- Module#===
mod === anObject -> true or false
------------------------------------------------------------------------
Case Equality---Returns true if anObject is an instance of mod or
one of mod's descendents. Of limited use for modules, but can be
used in case statements to classify objects by class.
EOD

The main thing here is that when you type Bignum === x, or Comparable ===
x, Ruby expects to be an Object. Now of course, everything is an Object,
but it is their TYPE that is being inspected.

So:

- Bignum === Bignum: the RHS is an object of type Class, which does not
feature in Bignum's ancestors; hence false.

- Kernel === Kernel: everything has Kernel included in it, so x ===
Kernel is always true.

- Object === Object: ditto (every Class is_a? Object)

- Comparable === Comparable: same as Bignum

- Bignum.id === Bignum.id: === reduces to == in this case (Fixnum), hence
true

In short, you're not using the === operator in the documented way.

Cheers,
Gavin


> Hi,
>
> I'm just noticing that some classes return true when testing
> themselves with #===, while others return false. For instance:
>
> (ruby 1.6.6 (2001-12-26) [i586-mswin32])
> irb> Bignum === Bignum
> false
> irb> Bignum.id === Bignum.id
> true
> irb> Bignum == Bignum
> true
> irb> Bignum.ancestors
> [Bignum, Integer, Precision, Numeric, Comparable, Object, Kernel]
> irb> Kernel === Kernel
> true
> irb> Object === Object
> true
> irb> Comparable === Comparable
> false
>
>
> . . . It appears Comparable may be the culprit? Though, I've
> noticed Enumerable introduces the same kind of behavior.
>
> Just wondering if this behavior is intentional, and if so, why?
>
>
> Thanks,
>
> Bill






<Prev in Thread] Current Thread [Next in Thread>
Google Custom Search

News | FAQ | advertise