Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby case statement does not perform as expected

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.

like image 832
David Nix Avatar asked Oct 22 '25 14:10

David Nix


2 Answers

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
like image 163
Jim Deville Avatar answered Oct 25 '25 05:10

Jim Deville


Ruby's case uses === (the case equality operator) to check equality.

While 0.class == Fixnum results in true, 0.class === Fixnum results in false.

like image 23
Oleg Mikheev Avatar answered Oct 25 '25 03:10

Oleg Mikheev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!