Lesson 3 of 11
Control Flow
Learn if, unless, case and Ruby's . Ruby offers readable forms such as `unless` (if not), `until` (while not) and conditions at the end of a line.
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# 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
endFinished reading?Mark it done to track your progress.
Tip: use the ← and → keys to move between lessons.