From: Rick DeNatale Date: 2006-09-11T00:25:11+09:00 Subject: Re: Puzzling bug with yielded array On 9/9/06, A. S. Bradbury wrote: > 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. Here's a recursive implementation of that then: def each_level(include_self=false, levels=[[]], depth=0) levels[depth] << self if include_self kids = self.children.values unless kids.empty? levels << [] unless levels.length > depth + 1 kids.each {|kid| kid.each_level(true, levels, depth+1)} end levels.each {|l| yield l} if depth.zero? end Although it might be better to make a public wrapper method to start, and make the internal recursive method private, so as not to expose the extra parameters: def each_level(include_self=false) levels = [] levels << [self] if include_self kids = self.children.values unless kids.empty? levels << [] kids.each {|kid| kid.each_level_internal(levels, 1)} end levels.each {|l| yield l} end private def each_level_internal(levels, depth) levels[depth] << self kids = self.children.values unless kids.empty? levels << [] unless levels.length > depth + 1 kids.each {|kid| kid.each_level_internal(levels, depth+1)} end end -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/