Difference between for loop and each by YuanYi Zhang | published: February 15,200 8
The main differences between for and each are:
- For is implemented by calling each, so for is slower.
- For creates a local variable outside the scope of each, which may cause problems in some cases.
The following code provides a good explanation of the problem:
irb> [1, 2, 3].each do |m| puts m end
irb> puts m
NameError: undefined local variable or method `m' for main:Object
irb> for n in [1, 2, 3] do puts n; end
irb> puts n
=> 3
If you do not understand this, you may encounter problems in some special circumstances. A piece of code submitted by a user in Ruby forum can explain the possible problems caused by:
a = []
for n in [1, 2, 3] do
a << Proc.new {puts "#{n}"}
end
[1,2,3].each do |m|
a << Proc.new {puts "#{m}"}
end
a.each { |p| p.call }
Running result:
3
3
3
1
2
3
Obviously, the results of the for loop are not what we expect. Therefore, the conclusion is:Use each instead of for loop as much as possible.
Update: Thanks to shiningray, the real reason why we should replace for with each is that for is actually implemented through each, but it defines a variable with the same name outside the scope of each, the following code describes the problem:
>> a = “1\n2\n”
>> def a.each
>> yield(1)
>> end
>> for i in a
>> puts i
>> end
1
=> nil
That is to say, "For I in [1, 2]" is equivalent to "I = nil; [1, 2]. each do | I | ", so the previous conclusion is incorrect. For should be slower than each (no tests have been conducted), which is the real problem of.
From: letrails. CN