David Nix
David Nix

Reputation: 3334

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.

Upvotes: 4

Views: 855

Answers (2)

Oleg Mikheev
Oleg Mikheev

Reputation: 17444

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

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

Upvotes: 3

Jim Deville
Jim Deville

Reputation: 10662

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

Upvotes: 8

Related Questions