Ruby conditionals: Difference between revisions
From wikinotes
(→Case) |
|||
(5 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
= If Statement = | = If Statement = | ||
<blockquote> | |||
<source lang="ruby"> | <source lang="ruby"> | ||
if platform == "linux" | if platform == "linux" | ||
puts "is linux" | puts "is linux" | ||
# if `platform` matches regex | elsif platform =~ /^win/ # if `platform` matches regex /^win/ | ||
puts "is windows variant" | puts "is windows variant" | ||
Line 15: | Line 15: | ||
<source lang="ruby"> | <source lang="ruby"> | ||
if 1 == 1 then puts "equal!" | if 1 == 1 then puts "equal!" | ||
else puts "not equal" | else puts "not equal" | ||
end | end | ||
</source> | </source> | ||
</blockquote><!-- If Statement --> | |||
= | = Unless = | ||
<blockquote> | |||
<source lang="ruby"> | <source lang="ruby"> | ||
unless | unless platform == "FreeBSD" | ||
puts " | puts "not FreeBSD" | ||
end | end | ||
</source> | </source> | ||
</blockquote><!-- Unless --> | |||
= | = Case = | ||
<blockquote> | |||
Tests value of capacity over several conditions. | Tests value of capacity over several conditions. | ||
Each expression is compared against the value using the <code>===</code> [[ruby operators|operator]]. | Each expression is compared against the value using the <code>===</code> [[ruby operators|operator]]. | ||
<source lang="ruby"> | <source lang="ruby"> | ||
case capacity | case capacity | ||
when 0 | when 0 # exact match | ||
" | "..." | ||
when 71..100 | when 50, 100 # either match | ||
" | "..." | ||
when /\AC/ | when 71..100 # within range | ||
" | "..." | ||
when /\AC/ # matches regex | |||
"..." | |||
when String # when instance of class | |||
"..." | |||
else | else | ||
"Error: capacity has an invalid value (#{capacity})" | "Error: capacity has an invalid value (#{capacity})" | ||
</source> | </source> | ||
</blockquote><!-- Case --> | |||
= | = Ternary Operator = | ||
<blockquote> | |||
<source lang="ruby"> | <source lang="ruby"> | ||
val = val_if_true ? condition : val_if_false | val = val_if_true ? condition : val_if_false | ||
</source> | </source> | ||
</blockquote><!-- Ternary Operator --> |
Latest revision as of 15:50, 14 May 2022
If Statement
if platform == "linux" puts "is linux" elsif platform =~ /^win/ # if `platform` matches regex /^win/ puts "is windows variant" else puts "not linux or windows" endif 1 == 1 then puts "equal!" else puts "not equal" end
Unless
unless platform == "FreeBSD" puts "not FreeBSD" end
Case
Tests value of capacity over several conditions. Each expression is compared against the value using the
===
operator.case capacity when 0 # exact match "..." when 50, 100 # either match "..." when 71..100 # within range "..." when /\AC/ # matches regex "..." when String # when instance of class "..." else "Error: capacity has an invalid value (#{capacity})"
Ternary Operator
val = val_if_true ? condition : val_if_false