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"
ShadowBelmolve 5 months ago
Strange...
loop1[1].call #=> "two"
loop2[1].call #=> "three"
ree 1.8.7
Paul Philippov 5 months ago
Sorry. my fault, The original code had these values. I've simplified the code but overlooked the output in comments. Changed the post to have correct values.
Marty Andrews 5 months ago
I wrote the Roodi check because Enumerable.each seems to be more idiomatic of Ruby code than for loops do. I commonly see people writing for loops when they're new to the language. For me, it *was* an issue of personal choice. People could always turn the check off if they don't like it.
I honestly wasn't aware of the differences you described above. Good to know though - thanks!
Paul Philippov 5 months ago
Marty, thank you for the Roodi. The more I use it, the more I like it =)