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
Post a Comment