String for array to multidimensional hash in ruby

I really don't know if the title is correct, but the question is pretty 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

+4
source share
3 answers

You can try to do this 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}}} 
+1
source

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}}} 
+1
source

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}}} 
+1
source

Source: https://habr.com/ru/post/1393119/


All Articles