From: Dustin Barker Date: 2008-06-11T05:02:06+09:00 Subject: Re: Basic Tree Data Structure No problem - so try out this snippet: t = Tree.new("a") t1 = t << "b" t1 << "c" t << "d" class Tree def each yield value @children.each do |child_node| child_node.each { |e| yield "node:#{value} yields:#{e}" } end end end t.each { |x| puts "each:#{x}" } here's some annotated output: each:a # (a) yield value each:node:a yields:b # (b) yield value - > (a) yield e each:node:a yields:node:b yields:c # (c) yield value -> (b) yield e -> (a) yield e each:node:a yields:d # (d) yield value - > (a) yield e Seems like you're traversing correctly, I think the 1,2,3 output might've been confusing. The output of this snippet illustrates how the calls stack up - each yield returns to the caller, which in turn yields to it's caller, and so on. -Dustin On Jun 10, 2008, at 3:04 PM, Justin To wrote: > Thanks Dustin, that clarifies one bit of the confusion, but I'm still > puzzled: > > Output: Parent > in child node > 3 Parent > Output: Child 1 > in child node > 3 Child 1 > 3 Parent # Q1: Why does it go through the Parent again? > Output: Grandchild 1.1 > > class Tree > def each > puts "1" > yield value # Q2: Which block does this invoke? > puts "2" > @children.each do |child_node| > puts "in child_node" > child_node.each { |e| puts "3"; yield e; } # Q3: Which block > does this > # yield invoke? > end > end > end > > t.each { |x| puts "t.each"; puts x } > > I'm trying hard to understand!! =D Thanks for the help! > -- > Posted via http://www.ruby-forum.com/. >