user2012677
user2012677

Reputation: 5735

If statement and Case statement - Not matching

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?

Upvotes: 4

Views: 53

Answers (1)

Amadan
Amadan

Reputation: 198324

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.)

Upvotes: 6

Related Questions