Ruby conditionals

From wikinotes
Revision as of 18:51, 23 April 2020 by Will (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

If Statement

if editor == "emacs"
  puts "is emacs"

# if `editor` contains 'vi' letters together anywhere in word
elsif editor =~ /vi/
  puts "is vi or vim"

else
  puts "not vi/vim/emacs"

end
if 1 == 1 then puts "equal!" 
else puts "not equal"
end

unless

unless editor == "vim"
  puts "your editor sux"
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