2018-10-08 00:07:46 +00:00
|
|
|
# Similar to a switch statement if you've used C/C++/Java, but Ruby's
|
|
|
|
# is a bit more powerful.
|
|
|
|
|
|
|
|
# Basic value tests
|
|
|
|
num = 5
|
|
|
|
case num
|
|
|
|
when 1
|
|
|
|
puts "it's one"
|
|
|
|
when 3
|
|
|
|
puts "wow, it's three"
|
|
|
|
when 5
|
|
|
|
puts "five golden rings"
|
|
|
|
end
|
|
|
|
|
|
|
|
# Ranges
|
|
|
|
num = 25
|
|
|
|
case num
|
|
|
|
when 1..10
|
|
|
|
puts "between one and ten"
|
|
|
|
when 20..30
|
|
|
|
puts "between twenty and thirty"
|
|
|
|
else
|
|
|
|
puts "must be between ten and twenty"
|
|
|
|
end
|
|
|
|
|
|
|
|
# Regular expressions
|
|
|
|
str = "doe, a deer"
|
|
|
|
case str
|
|
|
|
when /food/
|
|
|
|
puts "i'm hungry"
|
|
|
|
when /doe/
|
|
|
|
puts "#{str}, a female deer"
|
|
|
|
end
|
2019-10-15 09:03:35 +00:00
|
|
|
|
|
|
|
# Please note that `case` uses `===` operator to match values.
|
|
|
|
# The following are equivalent:
|
|
|
|
case x
|
|
|
|
when Integer then "I'm a number"
|
|
|
|
when String then "I'm a text"
|
|
|
|
end
|
|
|
|
|
|
|
|
if Integer === x
|
|
|
|
"I'm a number"
|
|
|
|
elsif String === x
|
|
|
|
"I'm a text"
|
|
|
|
end
|