Case question

Hello,

I am a little confused

irb(main):165:0* case nil.class
irb(main):166:1> when NilClass
irb(main):167:1> puts “hier”
irb(main):168:1> when Array
irb(main):169:1> puts “dort”
irb(main):170:1> else
irb(main):171:1* puts “aaa”
irb(main):172:1> end
aaa
=> nil
irb(main):173:0> nil.class
=> NilClass
irb(main):174:0>

it must miss something
Any ideas?

Regards, Daniel

On 1/9/06, Schüle Daniel [email protected] wrote:

irb(main):171:1* puts “aaa”
irb(main):172:1> end
aaa
=> nil
irb(main):173:0> nil.class
=> NilClass

case statements use the === operator for comparison, with the when
clause as receiver. So:

case arg
when condition: do_something
end

is the same as:

if (condition === arg)
do_something
end

In this case, invoking the === operator on a Class object (of which
NilClass is an instance) checks to see if the argument is an instance
of that class. NilClass is not an instance of NilClass, but of Class.
So if you’d written:

case nil.class
when NilClass: puts “hier”
when Array: puts “dort”
when Class: puts “xyz”
else puts “aaa”
end

You would have got “xyz” as the result. To do what you intended, just
leave off the call to #class on nil:

case nil
when NilClass: puts “hier”
when Array: puts “dort”
else puts “aaa”
end

That should print “hier”, since nil is an instance of NilClass.

Jacob F.

it must miss something
Any ideas?

case comparisons are done using ===.

irb(main):017:0> nil.class === NilClass
=> false
irb(main):018:0> nil.class == NilClass
=> true

For classes/modules, it’s used to determine if an instance is a
descendant:

irb(main):027:0> 5 === Fixnum
=> false
irb(main):028:0> Fixnum === 5
=> true

Caleb

can I assume that === is in this context the same as kind_of?
or are there subtle differences between them

=== by default calls == unless you specifically override it in your
implementation.

Module overrides it (which means that Class overrides it as well).

I think it’s probably safe to say that === is in the same context as
kind_of?,
at least for classes:

irb(main):009:0> NilClass === nil
=> true
irb(main):010:0> nil === NilClass
=> false

Caleb

Caleb T. wrote:

irb(main):018:0> nil.class == NilClass
=> true

For classes/modules, it’s used to determine if an instance is a
descendant:

nil.kind_of? NilClass

can I assume that === is in this context the same as kind_of?
or are there subtle differences between them

irb(main):027:0> 5 === Fixnum
=> false
irb(main):028:0> Fixnum === 5
=> true

Caleb

thanks to both, this helps