[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: case question

Jacob Fugal

1/10/2006 12:08:00 AM

On 1/9/06, Schüle Daniel <uval@rz.uni-karlsruhe.de> wrote:
> 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

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 Fugal