Conditions and loops
if / elsif / unless, case, iterating with each and times, while, and next / break.
Runs in Zerethon IDE · Ruby 4.0
Official Ruby documentation ↗
main.rb
(1..5).each do |n|
if n.even?
puts "#{n} even"
elsif n == 5
puts "#{n} last"
else
puts "#{n} odd"
end
end
i = 3
while i > 0
i -= 1
next if i == 1
puts "i = #{i}"
end
%w[apple pear].each_with_index { |fruit, index| puts "#{index} #{fruit}" }
day = 6
kind = case day
when 0, 6 then "weekend"
when 1..5 then "weekday"
end
puts kind
temperature = -2
puts "freezing" unless temperature > 0
puts 3.times.to_a.inspect
Output
1 odd 2 even 3 odd 4 even 5 last i = 2 i = 0 0 apple 1 pear weekend freezing [0, 1, 2]
1..5includes 5;1...5stops before it.- Every
if,while,doanddefblock ends withend. puts x if conditionandnext if conditionare one-line modifiers.- Ruby code rarely uses
for;each,times,uptoandeach_with_indexare the usual loops.