From: Eero Saynatkari Date: 2006-09-09T08:46:20+09:00 Subject: Re: Puzzling bug with yielded array 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 -- Posted via http://www.ruby-forum.com/.