From: James Edward Gray II Date: 2007-11-14T12:16:12+09:00 Subject: Re: recursion with blocks On Nov 13, 2007, at 9:11 PM, James Edward Gray II wrote: > On Nov 13, 2007, at 8:54 PM, Raul Parolari wrote: > >> James Gray wrote: >> >>> >>> Does this give you some ideas? >>> >>> 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 >>> .. >> >> I played with this Tree for a while (amazed by its simplicity and >> functionality); just a small problem when connecting (and printing) >> Trees to each other. A small touch to the << method does it: >> >> def <<(leaf_name) >> case leaf_name >> when String >> @leaves << self.class.new(leaf_name) >> when Tree >> @leaves << leaf_name >> else raise >> end >> self >> end > > Yeah, that's much better. I actually used a structure close to > this, with more niceties of course, for a binary tree I needed. I > was surprised at how easy it was to put together and how flexible > it was. I believe the actual each() method from that one was: > > def each(&block) > block[@left] if @left > block[self] > block[@right] if @right > end Sorry, should have looked it up: def each(&block) @left.each(&block) if @left block[self] @right.each(&block) if @right end James Edward Gray II