Ruby: Comparing an Object’s Class in a Case Statement

Posted on February 1, 2007
Filed Under /dev/ruby | 4,296 views |

Here's a little tidbit that I had to dig long and hard on Google to find. If you want to use a case statement in Ruby to act on the class of an object, the following - my initial attempt that I thought ought to work - won't work:

RUBY:
  1. def get_value( pResult )
  2.     case pResult.class
  3.       when Admin then pResult.username
  4.       when Client then pResult.title
  5.     end
  6.   end

I wrote that assuming that the case statement would do an is_a? comparison on the object class and return the correct result. Instead, it needs to be written as so:

RUBY:
  1. def get_value( pResult )
  2.     case pResult
  3.       when Admin: pResult.username
  4.       when Client: pResult.title
  5.     end
  6.   end

Comments

8 Responses to “Ruby: Comparing an Object’s Class in a Case Statement”

  1. Oscar on January 6th, 2008 3:34 pm

    Thanks, very helpful

  2. scrooloose on January 26th, 2008 8:27 pm

    Sweet, i was stumped till i found this. Thanks :)

  3. Chris on January 26th, 2008 11:16 pm

    Glad it was useful!

  4. Jim Cropcho on April 4th, 2008 6:44 pm

    i am part of the chorus saying “thank you.”

  5. Jim Cropcho on April 4th, 2008 6:50 pm

    alternative format:

    a = ”

    case a
    when Array
    puts ‘4′
    when String
    puts ‘5′
    else
    puts a.class
    end

  6. Mike Boone on July 10th, 2008 11:55 am

    Just ran into this issue today. Thanks!

  7. Red M@ on August 26th, 2008 11:21 am

    Very helpful.

    Note that Ruby gives me a warning using the “:” case syntax. I guess it’s depricated in favor of using “then”. Here’s current version:

    def get_value( pResult )
    case pResult
    when Admin then pResult.username
    when Client then pResult.title
    end
    end

  8. Chris on August 26th, 2008 11:51 am

    @Red M: looks to me like your version assumes that you’re passing in the class of the object as pResult instead of an object who’s class is then determined. Not quite the same thing but pretty close.

  • About

    This is an area on your website where you can add text. This will serve as an informative location on your website, where you can talk about your site.

  • Admin