Ruby class types and case statements

Daisy Sophia Hollman picture Daisy Sophia Hollman · Oct 11, 2010 · Viewed 43.8k times · Source

What is the difference between

case item.class
when MyClass
  # do something here
when Array
  # do something different here
when String
  # do a third thing
end

and

case item.class
when MyClass.class
  # do something here
when Array.class
  # do something different here
when String.class
  # do a third thing
end

For some reason, the first one of these works sometimes and the second doesn't, and other times, the second one works and the first one doesn't. Why? Which one is the "proper" way to do it?

Answer

Nakilon picture Nakilon · Oct 11, 2010

You must use:

case item
when MyClass
...

I had the same problem: How to catch Errno::ECONNRESET class in "case when"?