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

Saturn
  • 17,888
  • 49
  • 145
  • 271
  • 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... – Saturn Feb 09 '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 http://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. – Saturn Feb 10 '13 at 22:31
  • It's completely irrelevant what `case` desugars into. My question is why the OP thinks that the `#class` method would return anything other than a `Class`. My guess is that there is some shitty tutorial out there which teaches this, and I would like to know which tutorial that is, so that I can warn people about it. – Jörg W Mittag Feb 11 '13 at 01:45
  • @JörgWMittag: No tutorial - I just made a wrong assumption - you see, I supposed that `#class` would throw me a `String`, from where the case statement would compare `String == String`. But no, I was simply wrong because I didn't understand it well. That's all. – Saturn Feb 11 '13 at 02:04

1 Answers1

8

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
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Nevir
  • 7,951
  • 4
  • 41
  • 50