for and each
In this page:
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
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: