Saturn
Saturn

Reputation: 18149

Why are Ruby cases not working with classes?

case "Hello".class
  when Integer
      print "A"
  when String
      print "B"
  else
      print "C"
end

Why do I get "C"? Was expecting "B" since if you evaluate "String".class you do get String.

Upvotes: 5

Views: 383

Answers (1)

Nevir
Nevir

Reputation: 8101

Confusingly, Ruby's case statement uses === to compare each case to the subject. Class#=== tests for instances of that class, but not the class itself:

> Fixnum === Integer
false
> Fixnum === 1
true

The case behavior that Ruby is trying to promote is:

case "Hello"
  when Integer
    puts "A"
  when String
    puts "B"
  else
    puts "C"
end

Upvotes: 8

Related Questions