J
Jacob Fugal
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
=3D> nil
irb(main):173:0> nil.class
=3D> NilClass
case statements use the =3D=3D=3D operator for comparison, with the when
clause as receiver. So:
case arg
when condition: do_something
end
is the same as:
if (condition =3D=3D=3D arg)
do_something
end
In this case, invoking the =3D=3D=3D 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