From: "A. S. Bradbury" Date: 2006-09-09T19:46:46+09:00 Subject: Re: Puzzling bug with yielded array On Saturday 09 September 2006 00:46, Eero Saynatkari wrote: > Rick Denatale wrote: > > On 9/8/06, A. S. Bradbury wrote: > >> A more general question - how would you (ruby-talk readers) implement > >> this method? Two people on #ruby-lang suggested I make it recursive, but > >> I really don't see this sort of tree traversal mapping to a recursive > >> method, am I wrong? > > > > Tree traversal usually lends itself well to a recursive > > implementation, but it's not clear to me exactly what your each_level > > method is supposed to do. > > > > > > But here's a recursive implementation that might do the same thing. > > > > def each_level(include_self=false, &block) > > yield [self] if include_self > > kids = children.values > > unless kids.empty? > > yield kids > > kids.each do {|kid| kid.each_level(&block)} > > end > > end > > That is a semi-depth-first traversal, though. Apparently > we are looking for breadth-first here :) That would be > simplest to implement with some kind of a storage--say > an Array with an element for each level--which is sort > of what the OP's method was doing (though only for the > first three levels since it does not recurse). > > > Rick DeNatale Indeed, I am implementing a breadth-first or level-by-level traversal. I don't understand your comment about "only for the first three levels"? I can see other forms of tree traversal lending themselves well to a recursive implementation, but not really level by level, particular as I want each level to be returned as an array. Alex