Home > Uncategorized > Ruby: Comparing an Object’s Class in a Case Statement

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 Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.