[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Tricky: converting path into a Hash

Ara.T.Howard

1/22/2007 1:31:00 AM

2 Answers

William James

1/22/2007 2:13:00 AM

0

> 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"=>{}}}}

Daniel Berger

1/22/2007 4:16:00 AM

0


ara.t.howard@noaa.gov wrote:
> 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"=>{}}}}

I guess my question is....why?

Dan