Ruby conditionals

From wikinotes
Revision as of 15:50, 14 May 2022 by Will (talk | contribs) (→‎Case)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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"

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                        # 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