I am using Ruby 1.9.2 and Ruby on Rails 3.2.2. I have the following method:
# Note: The 'class_name' parameter is a constant; that is, it is a model class name.
def my_method(class_name)
case class_name
when Article then make_a_thing
when Comment then make_another_thing
when ... then ...
else raise("Wrong #{class_name}!")
end
end
I would like to understand why, in the case statement above, it always runs the else “part” when I execute method calls like my_method(Article), my_method(Comment) and so on.
How can I solve the issue? Does someone have advice how to handle this?
This is because
casecalls===, and===on Class (or specifically Module, which Class descends from) is implemented like so:This means that for any constant except
Class&Module(e.g.Foo),Foo === Fooalways returnsfalse. As a result, you always get theelsecondition in yourcasestatement.Instead just call
casewith the object itself, instead of its class, or useifstatements.