The Ruby
case
expression is a powerful beast: a multiway
if
on steroids.
case inputLine
when "debug"
dumpDebugInfo
dumpSymbols
when /p\s+(\w+)/
dumpVariable($1)
when "quit", "exit"
exit
else
print "Illegal command: #{inputLine}"
end
|
As with
if
,
case
returns the value of the last expression
executed, and you also need a
then
keyword if the
expression is on the same line as the condition.
kind = case year
when 1850..1889 then "Blues"
when 1890..1909 then "Ragtime"
when 1910..1929 then "New Orleans Jazz"
when 1930..1939 then "Swing"
when 1940..1950 then "Bebop"
else "Jazz"
end
|
case
operates by comparing the target (the expression after the
keyword
case
) with each of the comparison expressions after the
when
keywords. This test is done using
comparison ===
target.
As long as a class defines
meaningful semantics for
===
(and all the built-in classes do),
objects of that class can be used in case expressions.
For example, regular expressions define
===
as a simple pattern match.
case line
when /title=(.*)/
puts "Title is #$1"
when /track=(.*)/
puts "Track is #$1"
when /artist=(.*)/
puts "Artist is #$1"
end
|
Ruby classes are instances of class
Class
, which defines
===
as a test to see if the argument is an instance of the class or one of
its superclasses. So (abandoning the benefits of polymorphism and
bringing the gods of refactoring down around your ears), you can test
the class of objects:
case shape
when Square, Rectangle
# ...
when Circle
# ...
when Triangle
# ...
else
# ...
end
|