4

Why would the if statement work, but the case statement not work?

class A end # => nil a= A.new # => #<A:0x00007fd9d6134770> 

If statement works

a.class == A # => true 

Case statement does not work

case a.class # => A when A puts "done" else puts "else" # => nil end # => nil # >> else 

I read that case statement use === operators instead of ==, how do I use == for the case statement?

4
  • Try the if statement with case equality a.class === A. Commented Sep 25, 2019 at 2:59
  • Trying to do the reverse, a case statement with == Commented Sep 25, 2019 at 3:00
  • You can't use ==, it is always ===. Commented Sep 25, 2019 at 9:55
  • 1
    Possible duplicate of Ruby Case class check Commented Sep 25, 2019 at 9:56

1 Answer 1

6

The form case specific when archetype... will always use the archetype.===(specific) subsumption check. To use ==, you would need to be explicit, and use the other form: case when boolean:

case when a.class == A puts "done" else puts "else" end 

However, in this specific case (checking if an object belongs in a class), if you don't care whether a is an instance of A or an instance of a subclass of A (which is almost always the case), you can still use the subsumption check, like this:

case a # Note: not a.class when A puts "done" else puts "else" end 

because A === a when A is a class is pretty much the same as a.is_a?(A). Note that this is different from a.class == A, which will not be true if a is an instance of a subclass of A. For example for class Dog < Animal, and fido = Dog.new, both fido.instance_of?(Animal) and fido.class == Animal are false, but both fido.is_a?(Animal) and Animal === fido are true.)

Sign up to request clarification or add additional context in comments.

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.