Johandk
Johandk

Reputation: 428

ruby building hash from url

In Ruby, what is an efficient way to construct a Hash from a request path like:

/1/resource/23/subresource/34

into a hash that looks like this:

{'1' => { 'resource' => { '23' => 'subresource' => { '34' => {} } } }

Thanks

Upvotes: 1

Views: 110

Answers (2)

Casper
Casper

Reputation: 34308

path = "/1/resource/23/subresource/34"
path.scan(/[^\/]+/).inject(hash = {}) { |h,e| h[e] = {} }

hash
=> {"1"=>{"resource"=>{"23"=>{"subresource"=>{"34"=>{}}}}}}

Upvotes: 5

Emily
Emily

Reputation: 18193

A recursive solution seems like the simplest thing to do. This isn't the prettiest, but it works:

def hashify(string)
  k,v = string.gsub(/^\//, '').split('/', 2)  
  { k => v.nil? ? {} : hashify(v) }  
end 

There may be edge cases it doesn't handle correctly (probably are) but it satisfies the example you've given.

Upvotes: 1

Related Questions