From: Intransition Date: 2011-07-26T01:23:59+09:00 Subject: Re: Building a tree from the leaves down On Jul 21, 4:30 pm, Kendall Gifford wrote: > For fun, here's my OO-oriented approach with inspiration (though different) > from Robert's solution: > > class Hash >   INDENT = " " * 2 >   def inspect(indent = "") >     result    = "{\n" >     processed = 0 >     total     = count() >     each do |k, v| >       total  += 1 >       v       = v.is_a?(Hash) ? v.inspect(indent + INDENT) : v.inspect >       result << indent + INDENT + "#{k.inspect} => #{v}" >       result << "," if processed < total >       result << "\n" >     end >     "#{result}#{indent}}" >   end > end Always a good idea to make it easier to see what the hell is going on :-) > class Tree >   attr_reader :registry >   def initialize(parent = :parent) >     @parent   = parent >     @registry = {} >   end >   def register(node) >     parent = node.send(@parent) >     if parent >       @registry[parent]     ||= {} >       @registry[parent][node] = @registry[node] >       register(parent) >     end >   end >   def to_hash >     @registry.select { |k, v| k.send(@parent_method).nil? } >   end > end Nice, that's pretty easy to understand. Thanks. FYI, @parent_method, should be @parent.