T
Tom Cloyd
I'm studying the yield statement for the first time, today.
All's well until I see this example:
def myeach(myarray)
iter = 0
while (iter < myarray.length):
yield(myarray[iter])
iter += 1
end
end
testarray = [1,2,3,4,5]
myeach(testarray) {|item| print "#{item}:"}
→ 1:2:3:4:5:
I see a method with one parameter. There a block to the right of the
method call, inexplicably. It would make sense if some iteration were
going on, but I don't see that at all. One call, one execution (with a
loop), and we're out. What does "item" have to count through?
How can that yield do anything? How does it know about the block? It's
not passed in. The iteration appears to be happening IN the method,
using a block it cannot possibly see. Ouch! After some minutes, I'm not
getting this at all.
Can anyone clear my head for me. I've never seen anything like this. Or
is it just a weird Ruby idiom I'll just have to accept?
Thanks in advance.
Tom
--
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Tom Cloyd, MS MA, LMHC - Private practice Psychotherapist
Bellingham, Washington, U.S.A: (360) 920-1226
<< (e-mail address removed) >> (email)
<< TomCloyd.com >> (website)
<< sleightmind.wordpress.com >> (mental health weblog)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All's well until I see this example:
def myeach(myarray)
iter = 0
while (iter < myarray.length):
yield(myarray[iter])
iter += 1
end
end
testarray = [1,2,3,4,5]
myeach(testarray) {|item| print "#{item}:"}
→ 1:2:3:4:5:
I see a method with one parameter. There a block to the right of the
method call, inexplicably. It would make sense if some iteration were
going on, but I don't see that at all. One call, one execution (with a
loop), and we're out. What does "item" have to count through?
How can that yield do anything? How does it know about the block? It's
not passed in. The iteration appears to be happening IN the method,
using a block it cannot possibly see. Ouch! After some minutes, I'm not
getting this at all.
Can anyone clear my head for me. I've never seen anything like this. Or
is it just a weird Ruby idiom I'll just have to accept?
Thanks in advance.
Tom
--
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Tom Cloyd, MS MA, LMHC - Private practice Psychotherapist
Bellingham, Washington, U.S.A: (360) 920-1226
<< (e-mail address removed) >> (email)
<< TomCloyd.com >> (website)
<< sleightmind.wordpress.com >> (mental health weblog)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~