On Jun 10, 2008, at 4:58 PM, Justin To wrote:

> Output:
> each:a
> each:     node:a yields:b
> each:     node:a yields:     node:b yields:c
> each:     node:a yields:d
>
> Ok, from this example, I don't know how the #{e} in "child_node.each {
> |e| yield
> "node:#{value} yields:#{e}" }" turns into "node:b yields:c" because  
> the
> #{e} isn't calling yield is it?

That's right, the e doesn't call yield - the 'each' in child_node.each  
does. Remember that you're calling Tree#each here, so the value of 'e'  
is whatever is yielded by the 'each' method. You'll have as many e's  
as you have yields.

> Sorry for the trouble, I just can't seem to understand...when I walk
> through the algorithm with my logic it seems that it should just say
> "each: node b yields c"...which is obviously not the correct output.

So if remove the debug statements:

class Tree
   def each
     yield value
     @children.each do |child_node|
       child_node.each { |e| yield e }
     end
   end
end

t.each { |x| puts x }

I get:

a
b
c
d

Is that the iteration you're looking for? If so - let's walk through it:

t.each
-- yield value                                             # node a is  
yielding 'a' to t.each
puts x                                                          #  
t.each outputs 'a'
-- @children.each do |child_node|       # iterating children of node a
---- child_node.each                                # calling  
Tree#each for first child of a, which is node b
------ yield value                                        # node b is  
yielding 'b'
---- yield e                                                  # node a  
got e='b', so yielding 'b' to t.each
puts x                                                          #  
t.each outputs 'b'
------ @children.each do |child_node|  # iterating children of node b
-------- child_node.each                           # calling Tree#each  
for first child of b, which is node c
---------- yield value                                   # node c is  
yielding 'c'
------ yield e                                                # node b  
got e='c', so yielding 'c' to node a
---- yield e                                                   # node  
a got e='c', so yielding 'c' to t.each
puts x                                                           #  
outputs 'c'

>
>
> I'll continue reviewing your example, though, but if you can explain  
> in
> any other way, that'd be great. Thanks again!
>

No problem - it's a tough topic, hopefully the illustration of the  
calls above helps!

-Dustin