Ruby conditionals: Difference between revisions

From wikinotes
Line 21: Line 21:
= unless =
= unless =
<source lang="ruby">
<source lang="ruby">
unless editor == "vim"
unless platform == "FreeBSD"
   puts "your editor sux"
   puts "not FreeBSD"
end
end
</source>
</source>

Revision as of 22:27, 12 October 2021

If Statement

if platform == "linux"
  puts "is linux"

elsif editor =~ /^win/          # if `platform` matches regex /^win/
  puts "is windows variant"

else
  puts "not linux or windows"

end
if 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
  "You ran out of gas."
when 71..100
  "The tank is almost full."
when /\AC/
  "blah"
else
  "Error: capacity has an invalid value (#{capacity})"

ternary operator

val = val_if_true ? condition : val_if_false