Ok --
Phrogz, I find your script very interesting and I'll learn a lot by
going through it over and over. Thank you!
Paul, Sorry for the crappy data (it just happened to be what I was
working w/ at the time)
One of the key items both of you two used which I was not aware of
(and am ignorant for this) is the ability to use:
current = item_tree #Phrogz
node = tree # Paul
So what this is doing, is creating a new hash at the new depth,
without having to statically reference it. Nice. Yes, I'm a newb to
OO.
Thanks guys
On 10/30/06, x1 <caldridge@gmail.com> wrote:
> Jesus! Give me an hour or so to make sense of this. I'm so glad you
> provided this!! A++++++++++++
>
> On 10/30/06, Phrogz <gavin@refinery.com> wrote:
> > x1 wrote:
> > > Team:
> > > I'm looking for a pragmatic way of creating a tree from a list of
> > > items without knowing the depth of each.
> >
> > How about this:
> > class Hash
> > def as_tree( depth=0 )
> > map{ |k,subtree|
> > me = " "*depth + "#{k} (#{subtree.length})"
> > if subtree.empty?
> > me
> > else
> > [ me, subtree.as_tree( depth+1 ) ]
> > end
> > }.flatten.join( "\n" )
> > end
> > end
> >
> > hash_of_hashes = lambda { Hash.new {|h,k| h[k] = hash_of_hashes.call} }
> > item_tree = hash_of_hashes.call
> >
> > items = [ "CarRedFast", "CarGreenSlow", "Car",
> > "CarRedFastAgileSadCheeseBurger", "CarRedFastAgileHappyJoy",
> > "GreenApplePie", "GreenApple" ]
> > items.each do |item|
> > current = item_tree
> > item.scan( /[A-Z][a-z]+/ ).each{ |piece|
> > current = current[ piece ]
> > }
> > end
> >
> > puts item_tree.as_tree
> > #=> Green (1)
> > #=> Apple (1)
> > #=> Pie (0)
> > #=> Car (2)
> > #=> Red (1)
> > #=> Fast (1)
> > #=> Agile (2)
> > #=> Sad (1)
> > #=> Cheese (1)
> > #=> Burger (0)
> > #=> Happy (1)
> > #=> Joy (0)
> > #=> Green (1)
> > #=> Slow (0)
> >
> >
> >
>
>