Conditional structures/Ruby
if-then-else[edit]
<lang ruby>if s == 'Hello World'
foo
elsif s == 'Bye World'
bar
else
deus_ex
end</lang>
Note that if...end
is an expression, so its return value can be captured in a variable:
<lang ruby> s = 'yawn' result = if s == 'Hello World'
:foo elsif s == 'Bye World' :bar else :deus_ex end
- result now holds the symbol :deus_ex</lang>
ternary[edit]
<lang ruby> s == 'Hello World' ? foo : bar</lang>
case-when-else[edit]
A generic case statement <lang ruby>case when Time.now.wday == 5
puts "TGIF"
when rand(3) == 2
puts "had a 33% chance of being right"
else
puts "nothing special here"
end</lang> or, comparing to a specific object <lang ruby>case cartoon_character when 'Tom'
chase
when 'Jerry'
flee
end</lang>
For the second case, the comparisions are preformed using the ===
"case equality" method like this: 'Tom' === cartoon_character
. The default behaviour of ===
is simple Object#==
but some classes define it differently. For example the Module class (parent class of Class) defines ===
to return true if the class of the target is the specified class or a descendant:
<lang ruby>case some_object
when Numeric
puts "I'm a number. My absolute value is #{some_object.abs}"
when Array
puts "I'm an array. My length is #{some_object.length}"
when String
puts "I'm a string. When I'm down I look like this: #{some_object.downcase}"
else
puts "I'm a #{some_object.class}"
end</lang>
The class Regexp aliases ===
to =~
so you can write a case block to match against some regexes
<lang ruby>case astring
when /\A\Z/ then puts "Empty"
when /\Alower:+\Z/ then puts "Lower case"
when /\Aupper:+\Z/ then puts "Upper case"
else then puts "Mixed case or not purely alphabetic"
end</lang>
The class Range aliases ===
to include?
:
<lang ruby>case 79
when 1..50 then puts "low"
when 51..75 then puts "medium"
when 76..100 then puts "high"
end</lang>