Ruby: Comparing an Object’s Class in a Case Statement
Thanks to the o.b blog for this ruby tidbit. If you want to use an object’s class in a case statement in ruby the intuitive
case obj.class
when String: "blah"
when Fixnum: "foo"
end
doesn’t actually work? Why not you ask? Surely String == String will return true. Alas it seems we are now victims of ruby being too clever for it’s own good; if you’ve put class objects in the when clause you are obviously (?) wanting to compare the class of the object in the case statement. So ruby is helpfully inserting an extra .class call for you.
So if you want it to actually work
case obj
when String: "blah"
when Fixnum: "foo"
end
Advertisement
Categories: Uncategorized
ruby case class