Recursively set hash keys from an array of keys

I need a function that can take an array of type [:a, :b, :c]

and set the hash keys recursively, creating what it needs when it goes.

hash = {}

hash_setter(hash, [:a, :b, :c], 'value') 
hash #=> {:a => {:b => {:c => 'value' } } }

hash_setter(hash, [:a, :b, :h], 'value2') 
hash #=> {:a => {:b => {:c => 'value', :h => 'value2' } } }

      

I know Ruby 2.3 dig

can be used to get this way, although it doesn't give you an answer. If there was an equivalent to a setter that would be what I'm looking for.

+3


source to share


3 answers


code

def nested_hash(keys, v, h={})
  return subhash(keys, v) if h.empty?
  return h.merge(subhash(keys, v)) if keys.size == 1
  keys[0..-2].reduce(h) { |g,k| g[k] }.update(keys[-1]=>v)
  h
end

def subhash(keys, v)
  *first_keys, last_key = keys
  h = { last_key=>v }
  return h if first_keys.empty?
  first_keys.reverse_each.reduce(h) { |g,k| g = { k=>g } }
end

      

<strong> Examples

h = nested_hash([:a, :b, :c], 14)    #=> {:a=>{:b=>{:c=>14}}}
i = nested_hash([:a, :b, :d], 25, h) #=> {:a=>{:b=>{:c=>14, :d=>25}}}
j = nested_hash([:a, :b, :d], 99, i) #=> {:a=>{:b=>{:c=>14, :d=>99}}}
k = nested_hash([:a, :e], 104, j)    #=> {:a=>{:b=>{:c=>14, :d=>99}, :e=>104}}
    nested_hash([:f], 222, k)        #=> {:a=>{:b=>{:c=>14, :d=>99}, :e=>104}, :f=>222}

      

Note that the value is :d

overridden when calculated j

. Also note that:



subhash([:a, :b, :c], 12)
  #=> {:a=>{:b=>{:c=>12}}}

      

This mutates the hash h

. If this is not desired, you can insert the line

  f = Marshal.load(Marshal.dump(h))

      

after the line return subhash(keys, v) if h.empty?

and change subsequent references h

to f

. Methods from the Marshal module can be used to create a deep copy of the hash, so the original hash will not be mutated.

0


source


Solved the recursion:



def hash_setter(hash, key_arr, val)
  key = key_arr.shift
  hash[key] = {} unless hash[key].is_a?(Hash)
  key_arr.length > 0 ? hash_setter(hash[key], key_arr, val) : hash[key] = val
end

      

0


source


def set_value_for_keypath(initial, keypath, value)
    temp = initial

    for key in keypath.first(keypath.count - 1)
        temp = (temp[key] ||= {})
    end

    temp[keypath.last] = value

    return initial
end

initial = {:a => {:b => {:c => 'value' } } }

set_value_for_keypath(initial, [:a, :b, :h], 'value2')

initial

      

Or, if you prefer something a little more unreadable:

def set_value_for_keypath(initial, keypath, value)
    keypath.first(keypath.count - 1).reduce(initial) { |hash, key| hash[key] ||= {} }[keypath.last] = value
end

      

-2


source







All Articles