Ruby Tip #3: Matching on an Object's Class in a Case Expression
From time to time you might want to take different actions depending on an object’s class. One handy way to do so is with a case expression:
1
2
3
4
5
case object
when Fixnum then puts 'Object is an integer number'
when String then puts 'Object is a string'
when Hash then puts 'Object is a hash'
end
Behind the scenes this is transformed to:
1
2
3
4
5
6
7
if Fixnum === object
puts 'Object is an integer number'
elsif String === object
puts 'Object is a string'
elsif Hash === object
puts 'Object is a hash'
end
A lot of people seem to make the following mistake, so beware:
1
2
3
4
5
6
# WRONG - Class === Class will return false
case object.class
when Fixnum then puts 'Object is an integer number'
when String then puts 'Object is a string'
when Hash then puts 'Object is a hash'
end
Hopefully you’ll find this small tip useful.
This post is licensed under CC BY 4.0 by the author.