On Nov 13, 2007, at 3:49 PM, Mike Perham wrote: > I have a tree structure where I want to walk the structure and find a > node based on a name. I'm unclear how to use recursion with blocks > such > that I can return the correct node. All code snippets I've seen have > involved using "puts" to print out a node i.e. not returning > anything to > the top-level caller. What's the idiomatic Ruby for doing this? > How do > I return a value from a block called recursively? Does this give you some ideas? #!/usr/bin/env ruby -wKU class Tree def initialize(name) @name = name @leaves = Array.new end attr_reader :name def <<(leaf_name) @leaves << self.class.new(leaf_name) self end include Enumerable def each(&block) block[self] @leaves.each { |leaf| leaf.each(&block) } end def to_s(indent = String.new) str = "#{indent}#{@name}\n" @leaves.each { |leaf| str += leaf.to_s(indent + " ") } str end end tree = Tree.new("top") tree << "left" << "right" tree.find { |leaf| leaf.name == "right" } << "deep" puts tree __END__ James Edward Gray II