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

for and each

for goes through items one at a time, but Ruby fans prefer each, which does the same job in a more Ruby style. It is like two ways of walking down a row of desks.

In this page:

  1. for and each
Syntax
ruby
for item in collection
  # body
end

collection.each do |item|
  # body
end

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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Expecting a for loop to have its own scope, when the loop variable i stays available after the loop.
  2. Using for with a large or changing collection out of habit, when each is the idiomatic choice.
  3. Using 1..3.each without parentheses, calling each on 3 instead of the range.
🔒

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.