Differences between for loop and each

Source: Internet
Author: User
Difference between for loop and each by YuanYi Zhang | published: February 15,200 8

The main differences between for and each are:

  1. For is implemented by calling each, so for is slower.
  2. 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.