Conditional structures/Ruby: Difference between revisions

no edit summary
imported>Katsumi
No edit summary
 
Line 2:
 
===if-then-else===
<syntaxhighlight lang="ruby">
<lang ruby>if s == 'Hello World'
foo
elsif s == 'Bye World'
Line 8 ⟶ 9:
else
deus_ex
end</lang>
</syntaxhighlight>
 
Note that <code>if...end</code> is an expression, so its return value can be captured in a variable:
 
<langsyntaxhighlight lang="ruby">
 
s = 'yawn'
result = if s == 'Hello World'
Line 21 ⟶ 24:
:deus_ex
end
# result now holds the symbol :deus_ex</lang>
</syntaxhighlight>
 
===ternary===
<syntaxhighlight lang="ruby">
<lang ruby> s == 'Hello World' ? foo : bar</lang>
</syntaxhighlight>
 
===case-when-else===
A generic case statement
<langsyntaxhighlight lang="ruby">case
case
when Time.now.wday == 5
puts "TGIF"
Line 35 ⟶ 42:
else
puts "nothing special here"
end</lang>
</syntaxhighlight>
or, comparing to a specific object
<syntaxhighlight lang="ruby">
<lang ruby>case cartoon_character
when 'Tom'
chase
when 'Jerry'
flee
end</lang>
</syntaxhighlight>
 
For the second case, the comparisions are preformed using the <code>===</code> "case equality" method like this: <code>'Tom' === cartoon_character</code>. The default behaviour of <code>===</code> is simple <code>Object#==</code> but some classes define it differently. For example the Module class (parent class of Class) defines <code>===</code> to return true if the class of the target is the specified class or a descendant:
<syntaxhighlight lang ="ruby">case some_object
case some_object
when Numeric
puts "I'm a number. My absolute value is #{some_object.abs}"
Line 54 ⟶ 65:
else
puts "I'm a #{some_object.class}"
end</lang>
</syntaxhighlight>
 
The class Regexp aliases <code>===</code> to <code>=~</code> so you can write a case block to match against some regexes
<syntaxhighlight lang ="ruby">case astring
case astring
when /\A\Z/ then puts "Empty"
when /\A[[:lower:]]+\Z/ then puts "Lower case"
when /\A[[:upper:]]+\Z/ then puts "Upper case"
else then puts "Mixed case or not purely alphabetic"
end</lang>
</syntaxhighlight>
 
The class Range aliases <code>===</code> to <code>include?</code>:
<syntaxhighlight lang ="ruby">case 79
case 79
when 1..50 then puts "low"
when 51..75 then puts "medium"
when 76..100 then puts "high"
end</lang>
</syntaxhighlight>
Anonymous user