Skip to content
Loops and Iterators
step 1/5

Reading — step 1 of 5

Learn

~1 min readControl Flow

Ruby has standard loops, but you'll mostly use iterators — methods that yield each element to a block.

# Standard
while n > 1
    n /= 2
end

until ready do
    sleep 1
end

for i in 1..5      # works but rarely used
    puts i
end

# Idiomatic — block-based iterators
5.times { |i| puts i }
(1..5).each { |i| puts i }
[1, 2, 3].each { |x| puts x }

A block ({ |args| ... } or do |args| ... end) is a chunk of code that gets passed to a method. Most enumerable methods (each, map, select, reduce) take blocks.

Use {} for one-liners; do/end for multi-line. Use next to skip to the next iteration; break to exit the loop.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…