[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

Logan Capaldo

1/22/2007 1:48:00 AM

On Mon, Jan 22, 2007 at 10:15:09AM +0900, 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?
>
path = "a/b/c"

def hashify_path( s )
if s =~ %r{\A[^/]*\z}
{ s => {} }
elsif s =~ %r{\A([^/]*)/(.*)\z}
{ $1 => hashify_path( $2 ) }
else
raise ArgumentError, "Invalid path"
end
end

p hashify_path( path )

prints:
{"a"=>{"b"=>{"c"=>{}}}}
>
>
> Muchas Gracias Senoritas,
> Robert Mannl