chillibear.com

Ruby class and case statements

I was writing some code akin to:

case something.class
  when String, Symbol then 1
  when Fixnum then 2
  when Time then 3
end

Only to find it didn’t work, always returning nil. A bit of trawling turned up the following blog post: http://www.postal-code.com/mrhappy/blog/2007/02/01/ruby-comparing-an-objects-class-in-a-case-statement/, which explains that you don’t need the .class. So my above code would become:

case something
  when String, Symbol then 1
  when Fixnum then 2
  when Time then 3
end

Which works perfectly.

Written on 27 Oct 2010 and categorised in Ruby, tagged as case

Home, Post archive

site copyright Eric Freeman

Valid XHTML 1.0 Strict