String to array to multidimensional hash in ruby

String to array to multidimensional hash in ruby

I don't really know if the title is correct, but the question is quite simple:
I have a value and a key.
The key is as follows:
"one.two.three"
Now, how can I set this hash:
params['one']['two']['three'] = value

Solutions/Answers:

Answer 1:

You can try to do it with this code:

keys = "one.two.three".split '.' # => ["one", "two", "three"]
params = {}; value = 1; i = 0;  # i is an index of processed keys array element
keys.reduce(params) { |hash, key|
    hash[key] = if (i += 1) == keys.length
      value # assign value to the last key in keys array
    else
      hash[key] || {} # initialize hash if it is not initialized yet (won't loose already initialized hashes)
    end
}
puts params # {"one"=>{"two"=>{"three"=>1}}}

Answer 2:

Use recursion:

def make_hash(keys)
  keys.empty? ? 1 : { keys.shift => make_hash(keys) }
end

puts make_hash("one.two.three".split '.')
# => {"one"=>{"two"=>{"three"=>1}}}

Answer 3:

You can use the inject method:

key = "one.two.three"
value = 5

arr = key.split(".").reverse
arr[1..-1].inject({arr[0] => value}){ |memo, i| {i => memo} }
# => {"one"=>{"two"=>{"three"=>5}}}

References

Loading...