1

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

Johandk
  • 428
  • 3
  • 11

2 Answers2

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

hash
=> {"1"=>{"resource"=>{"23"=>{"subresource"=>{"34"=>{}}}}}}
Casper
  • 33,403
  • 4
  • 84
  • 79
  • 1
    The same, but if we go in reverse order: `path.scan(/[^\/]+/).reverse.inject({}) { |h,e| {e => h} }`. Might be a little more clear, and anyway, it is a one-liner: it already returns what we want. – NIA Feb 04 '13 at 20:01
1

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.

Emily
  • 17,813
  • 3
  • 43
  • 47