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:
Syntax
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
for i in 1..3
puts "for loop: #{i}"
end
(1..3).each do |i|
puts "each loop: #{i}"
end
Login to try C/C++/Java/PHP code in the editor
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
- Expecting a
forloop to have its own scope, when the loop variableistays available after the loop. - Using
forwith a large or changing collection out of habit, wheneachis the idiomatic choice. - Using
1..3.eachwithout parentheses, callingeachon3instead of the range.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: