the difference between for-loop and each

A

Andreas S

Hopefully (I'm sure) somebody can shed a light on this. This caught me by s=
urprise

test.rb:
TEST =3D []
def procs &block
TEST << block
end

#for n in [1,2,3] do
[1,2,3].each do |n|
procs do
puts "#{n}"
end
end

TEST.each do |t|
puts t
t.call
end

With for loop#
3
#
3
#
3

With each#
1
#
2
#
3

I thought for-loop behaves the same as each. Apparently not. Why is this an=
d is this a good thing?

Thank you in advance
-andre
_________________________________________________________________
Climb to the top of the charts!=A0 Play Star Shuffle:=A0 the word scramble =
challenge with star power.
http://club.live.com/star_shuffle.aspx?icid=3Dstarshuffle_wlmailtextlink_oc=
t=
 
R

Robert Klemme

Hopefully (I'm sure) somebody can shed a light on this. This caught me by surprise

test.rb:
TEST = []
def procs &block
TEST << block
end

#for n in [1,2,3] do
[1,2,3].each do |n|
procs do
puts "#{n}"
end
end

TEST.each do |t|
puts t
t.call
end

With for loop#
3
#
3
#
3

With each#
1
#
2
#
3

I thought for-loop behaves the same as each. Apparently not. Why is this and is this a good thing?

The reason for the behavior you are seeing is different scoping. "for"
does not open a new scope while block parameters sit in a different
scope. Apart from that "for" is a keyword (i.e. part of the language)
while "each" is just a method like other methods.

irb(main):014:0> def f1(x) x.each {|y| p y}; p y end
=> nil
irb(main):015:0> def f2(x) for y in x; p y; end; p y end
=> nil
irb(main):016:0> f1 %w{foo bar baz}
"foo"
"bar"
"baz"
NameError: undefined local variable or method `y' for main:Object
from (irb):14:in `f1'
from (irb):16
from :0
irb(main):017:0> f2 %w{foo bar baz}
"foo"
"bar"
"baz"
"baz"
=> nil
irb(main):018:0>

I'd say it's a good thing because you get the choice - if you need the
iteration variable after the block then use "for" - otherwise use "each".

Kind regards

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top