The Relationship Between "each" and "for"
Author |
Message |
wtd
|
Posted: Wed Jul 13, 2005 10:45 pm Post subject: The Relationship Between "each" and "for" |
|
|
It's the question that's as old as any I can remember. Should I use "for" or should I use the "each" method?
To answer that on a case-by-case basis, we have to understand both ways, how they're similar, and how they differ.
The "for" loop is made possible by the "each" method. Any class which implements "each" can use the for loop. Let's look at a simple nonsense example.
code: | class Qux
def each
yield 37
yield 53
yield 78
end
end |
Now I can just:
code: | for x in Qux.new
puts x
end |
And of course, I can call "each" directly.
code: | Qux.new.each { |x| puts x } |
So, what's the difference, except that "for" looks a bit nicer for long loops, and "each" has a certain charm for the simple stuff?
Scope is the issue. A variable created inside of a "for" loop is still in scope when the loop finishes. However, variables created within blocks attached to calls to "each" are local to the block, and don't affect the outer scope. |
|
|
|
|
|
Sponsor Sponsor
|
|
|
|
|