ruby - Set hash value at arbitrary location -


i working on application i'd modify part of existing hash looks like:

{a: {b: {c: 23}}} 

to be:

{a: {b: {c: [23]}}} 

however, exact key set dynamic , @ unknown depth in hash. there way set value in hash given array of keys? i'm hoping like:

my_hash['a','b','c'] = new_value 

getting value arbitrary depth straightforward via recursion, since traversal works on copies of data, rather references, don't know way set value without rebuilding entire array during traversal.

except syntax (my_hash['a','b','c']), following want

h = {a: {b: {c: { e: 23}}, d: 34}} keys = ['a','b','c']  def replace_nested_value_by(h, keys, value)   if keys.size > 1     replace_nested_value_by(h[keys.first.to_sym], keys[1..-1], value)   elsif keys.size == 1     h[keys.first.to_sym] = value   end end  puts h replace_nested_value_by(h, keys, 42) puts h 

Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -