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:
-
def get_value( pResult )
-
case pResult.class
-
when Admin then pResult.username
-
when Client then pResult.title
-
end
-
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:
-
def get_value( pResult )
-
case pResult
-
when Admin: pResult.username
-
when Client: pResult.title
-
end
-
end
Comments
8 Responses to “Ruby: Comparing an Object’s Class in a Case Statement”
Thanks, very helpful
Sweet, i was stumped till i found this. Thanks
Glad it was useful!
i am part of the chorus saying “thank you.”
alternative format:
a = ”
case a
when Array
puts ‘4′
when String
puts ‘5′
else
puts a.class
end
Just ran into this issue today. Thanks!
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
@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.