Control Flow
Ruby gives you plenty of ways to control program flow. if/elsif/else for conditions, or unless for the opposite. You can even use them as one-line modifiers at the end of a line. case/when handles multiple conditions elegantly. Loops? Try while/until, for-in, or the Ruby way: .times and .each. Use break to exit early and next to skip iterations. Everything in Ruby returns a value.
# if / elsif / else
age = 20
if age < 13
puts "child"
elsif age < 18
puts "teenager"
else
puts "adult"
end
# unless โ the opposite of if
unless age < 18
puts "You can vote!"
end
# Modifier form โ one-liners
puts "adult" if age >= 18
puts "underage" if age < 18
# case / when
day = "Monday"
case day
when "Monday"
puts "Start of the week"
when "Friday"
puts "Almost weekend!"
when "Saturday", "Sunday"
puts "Weekend!"
else
puts "Regular day"
end
# while loop
counter = 0
while counter < 5
puts counter
counter += 1
end
# until loop โ runs while condition is false
counter = 0
until counter == 5
puts counter
counter += 1
end
# for-in loop
for i in 1..5
puts i
end
# .times โ the Ruby way
5.times { |i| puts i }
# .each on ranges
(1..5).each { |i| puts i }
# break and next
5.times do |i|
next if i == 2 # skip 2
break if i == 4 # stop at 4
puts i
end
# Output: 0, 1, 3
Try it Yourself ->