Take the 2-minute tour ×
case "Hello".class
  when Integer
      print "A"
  when String
      print "B"
      print "C"

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

share|improve this question
Lots of votes for closing this! I'm sorry :(..., but why is this a bad question? I just found an odd behavior in Ruby I could not understand... –  Just Kidding Feb 9 '13 at 22:26
Why would you expect B? "Hello".class is obviously a Class and neither an Integer nor a String, so C is the only sensible answer here. –  Jörg W Mittag Feb 10 '13 at 11:40
@JörgWMittag perhaps the OP didn't know that case statements use === rather than ==. –  Andrew Grimm Feb 10 '13 at 22:03
A related (but not identical) question you (Omega) may be interested in is stackoverflow.com/q/9537895/38765 –  Andrew Grimm Feb 10 '13 at 22:03
@JörgWMittag: Oh I don't know - perhaps I'm too new to Ruby and didn't know that the case statement used ===? You may find it obvious, which is great, but I don't, thanks. –  Just Kidding Feb 10 '13 at 22:31
show 2 more comments

1 Answer

up vote 4 down vote accepted

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
> Fixnum === 1

The case behavior that Ruby is trying to promote is:

case "Hello"
  when Integer
    puts "A"
  when String
    puts "B"
    puts "C"
share|improve this answer
add comment

Your Answer


