Ruby case statement not working as expected

Fyi using Rails.

Considering user = User.find(1)

This case statement returns nil

when it should return a result 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.

+3


source to share


2 answers


Ruby operator is case

much more flexible than most other operators switch

. It uses an operator ===

, not an operator ==

. Classes define operator ===

along lines

def === (other) other.is_a? self #self - class end



So what you really want here:

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

      

+7


source


Ruby case

uses the ===

( equality operator ) to test for equality.



While 0.class == Fixnum

returning true, 0.class === Fixnum

results in false.

+3


source







All Articles