RbRuby · Lesson 3 of 11

Control Flow

Ruby's control flow reads like English prose. `unless` is `if not`. `until` is `while not`. You can put conditions at the end of a line. Matz really meant it about the happiness thing.

Ruby
age = 20

if age >= 18
  puts "adult"
elsif age >= 13
  puts "teenager"
else
  puts "child"
end

# unless = if not
unless age < 18
  puts "can vote"
end

# Modifier form — condition at end of statement
puts "adult" if age >= 18
puts "minor" unless age >= 18

# Ternary
label = age >= 18 ? "adult" : "minor"

# case / when (like switch)
grade = "B"
result = case grade
  when "A" then "Excellent"
  when "B" then "Good"
  when "C" then "Average"
  else "Below average"
end
puts result   # Good

# case with ranges
case age
when 0..12  then puts "child"
when 13..17 then puts "teenager"
when 18..64 then puts "adult"
else             puts "senior"
end
Ruby
# Loops
# times — most common for counted iterations
5.times { puts "hello" }

# upto / downto
1.upto(5)   { |i| print "#{i} " }   # 1 2 3 4 5
5.downto(1) { |i| print "#{i} " }   # 5 4 3 2 1

# loop with break
count = 0
loop do
  count += 1
  break if count >= 5
end

# while
i = 0
while i < 3
  puts i
  i += 1
end

# until (while not)
i = 10
until i <= 0
  i -= 3
end

# next = continue, break = break
(1..10).each do |n|
  next if n.even?
  break if n > 7
  puts n   # 1, 3, 5, 7
end
✦ Tip
Ruby has no `do...while`. The idiom is `loop do ... break if condition end`. Also: `case/when` is more powerful than most switch statements — it can match ranges, regexes, classes (via `===`), and arbitrary conditions.