← Back to Ruby Course | Chapter 6: Control Flow | Lesson 5 of 7

for and each

In this page:

  1. for and each

for and each

Ruby has a for item in collection loop, but idiomatic Ruby almost always prefers collection.each { |item| ... } instead, since each doesn't leak its loop variable into the surrounding scope the way for does. each is a method call on the collection itself, fitting Ruby's block-and-method-driven style better than a separate loop keyword. You'll rarely see for in real Ruby code.

Warning: for leaks its loop variable into the enclosing scope after the loop ends, while each's block variable stays properly scoped -- another reason each is preferred.

Example: for and each

markup
for i in 1..3
  puts "for loop: #{i}"
end

(1..3).each do |i|
  puts "each loop: #{i}"
end
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.