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 case statement is much more flexible than most other switch statements. It uses the === operator, not the == operator. Classes define the === operator along the lines of
def ===(other) other.is_a? self #self is the class end
So, what you actually want here is:
def case_method
case self
when User
do_something_with_user
when SomeOtherClass
do_something_else
end # else is un-needed as it will return nil by default
end
Ruby's case uses === (the case equality operator) to check equality.
While 0.class == Fixnum results in true, 0.class === Fixnum results in false.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With