BeginnerLesson 4 of 16
Loops and Iterators – Ruby
times, each, upto, step, while, until and loop.
In Ruby you rarely write classic counting loops. Instead you call iterator methods with a block: times, each, upto, step.
3.times { |i| puts "Round #{i}" }
1.upto(3) { |i| print i, " " }
puts
10.step(1, -3) { |i| print i, " " } # 10 7 4 1
puts
(1..5).each { |i| print i * i, " " } # 1 4 9 16 25
puts
%w[Apfel Birne Kirsche].each_with_index do |frucht, i|
puts "#{i + 1}. #{frucht.upcase}"
endRanges: 1..5 includes the 5, 1...5 does not. For condition-based loops there are while, until and loop. next jumps to the next round, break ends the loop.
n = 0
while true
n += 1
next if n.even?
break if n > 7
print n, " " # 1 3 5 7
end
puts
zahl = 1
zahl *= 2 until zahl > 100
puts zahl # 128
i = 0
loop do
i += 1
break if i == 3
end
puts i # 3TipYou write single-line blocks with
{ ... }, multi-line ones with do ... end. This is a convention – the difference lies only in binding strength (important for calls without parentheses).WarningRuby does have
for i in 1..3, but it does not create its own scope (the variable i stays visible afterwards) and is hardly used by Rubyists. Stick with each.