Case comparisons use ===
rather than ==
. For many objects the behaviour of ===
and ==
is the same, see Numeric
and String
:
5 == 5 #=> true
5 === 5 #=> true
"hello" == "hello" #=> true
"hello" === "hello" #=> true
But for other kinds of object ===
can mean many things, entirely depending on the receiver.
For the case of classes, ===
tests whether an object is an instance of that class:
Class === Class.new #=> true.
For Range it checks whether an object falls in that range:
(5..10) === 6 #=> true
For Procs, ===
actually invokes that Proc
:
multiple_of_10 = proc { |n| (n % 10) == 0 }
multiple_of_10 === 20 #=> true (equivalent to multiple_of_10.call(20))
For other objects, check their definition of ===
to uncover their behaviour. It's not always obvious, but they usually make some kind of sense..
Here is an example putting it all together:
case number
when 1
puts "One"
when 2..9
puts "Between two and nine"
when multiple_of_10
puts "A multiple of ten"
when String
puts "Not a number"
end
See this link for more info: http://www.aimred.com/news/developers/2008/08/14/unlocking_the_power_of_case_equality_proc/