Ruby conditionals: Difference between revisions

From wikinotes
No edit summary
 
Line 1: Line 1:
= If Statement =
= If Statement =
<source lang="ruby">
<source lang="ruby">
if editor == "emacs"
if platform == "linux"
   puts "is emacs"
   puts "is linux"


# if `editor` contains 'vi' letters together anywhere in word
# if `platform` matches regex /win/
elsif editor =~ /vi/
elsif editor =~ /^win/
   puts "is vi or vim"
   puts "is windows variant"


else
else
   puts "not vi/vim/emacs"
   puts "not linux or windows"


end
end

Revision as of 22:20, 12 October 2021

If Statement

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

# if `platform` matches regex /win/
elsif editor =~ /^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 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