Paul Philippov

home is where ~/ is

Enumerable.each vs 'for' loops in Ruby

A few days ago I checked the code using the Ruby project roodi, and I received a warning saying “Don’t use ‘for’ loops. Use Enumerable.each instead.” I personally do not see any difference between these two versions of cycles, and attributed the problem of choice to issues of personal faith. I asked people in the !ruby group of identi.ca, but the answers were not convincing. Google also did not shed light on this question.

I changed the code to use Enumerable.each, just in case, and put the problem aside. But today, I found a sample code, that clearly demonstrates the difference:

loop1 = []
loop2 = []

calls = ["one", "two", "three"]

calls.each do |c|
  loop1 << Proc.new { puts c }
end

for c in calls
  loop2 << Proc.new { puts c }
end

loop1[1].call #=> "two"
loop2[1].call #=> "three"

Published on March 08, 2010 (about 7 years ago)

Article tags: loop, ruby