Ruby class types and case statements

case-statementduck-typingruby

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?

Best Answer

You must use:

case item
when MyClass
...

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