4

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.

1
  • 2
    What does do_something_with_user return? Is it possible that it returns nil? Try debug printing to determine exactly which branch gets executed. Commented Jan 22, 2013 at 5:45

2 Answers 2

8

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 
Sign up to request clarification or add additional context in comments.

Comments

3

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.