Fyi, using Rails.
Given user = User.find(1)
This case statement returns nil when it should return the result of self.do_something_with_user.
def case_method
case self.class
when User
self.do_something_with_user # assume does not return nil
when SomeOtherClass
self.do_something_else
else
nil
end
end
user.case_method # => nil
What am I missing? Using pry, self.class == User returns true.
Ruby’s
casestatement is much more flexible than most otherswitchstatements. It uses the===operator, not the==operator. Classes define the===operator along the lines ofdef ===(other)
other.is_a? self #self is the class
end
So, what you actually want here is: