Skip to content
Lesson 7 of 15

Step 1 of 5 · Reading · ~1 min

Learn

Control 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.

Up nextDefining MethodsMethods and Blocks

Discussion

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

Sign in to post a comment or reply.

Loading…