Jon Canady

 

Switching on object class in Ruby

So it turns out, if you're trying to do one of these:

1 case obj.class
2   when ActiveRecord::Base: # do something
3   else # do something else
4 end

it always falls through to the else, no matter what obj happens to be!

Here's how that's done instead:

1 case obj # just use the object itself
2   when ActiveRecord::Base: # do something
3   else # do something else
4 end

My next exercise is figuring out why this is.