William James
1/22/2007 2:13:00 AM
> On Mon, 22 Jan 2007, Robert MannI wrote:
>
> > Hello!
> >
> >
> > I am wondering if the mighty ruby crowd has a brilliant idea for a tricky
> > problem I am solving.
> >
> > I need to store a path as a tree in a hash.
> >
> > Given:
> > a/b/c
> >
> > I want the Hash:
> > { 'a' => { 'b' => { 'c' => { } } } }
> > or written differently
> > hsh['a']['b']['c'] = {}
> >
> > Is there an elegant solution to this, without maybe looping or eval'ing too
> > much?
> >
>
> harp:~ > cat a.rb
> require 'pathname'
>
> class Pathname
> def to_hash
> ret = h = {}
> each_filename{|part| h[part] = (h={})}
> ret
> end
> end
>
> pn = Pathname.new 'a/b/c'
>
> p pn.to_hash
>
>
> harp:~ > ruby a.rb
> {"a"=>{"b"=>{"c"=>{}}}}
barf:~ > dog a.rb
s = "a/b/c"
p s.split("/").reverse.inject({}){|h,s| {s,h} }
barf:~ > ruby a.rb
{"a"=>{"b"=>{"c"=>{}}}}