H
H
himik2012-12-13 11:55:42
ruby
himik, 2012-12-13 11:55:42

How to set the value of a hash element from an array of keys?

Available

hash = {:a => {:b => [{:c => old_val}]}}
keys = [:a, :b, 0, :c]
new_val = 10

As a result, it is necessary that hash[:a][:b][0][:c] == new_val
The structure of the hash and the set of keys can change arbitrarily.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
H
himik, 2012-12-13
@himik

in general, the solution was found. thanks to all )

a = {:a => {:b => [{:c => 1}]}}
b = [:a, :b, 0, :c]
d = b.pop
b.inject(a) {|s,k| s[k]}[d] = 20

S
sl_bug, 2012-12-13
@sl_bug

here's a crutch for you :) here I think it can be significantly improved.

temp = hash
keys[0..-2].each do |k|
  temp = temp.send(:'[]', k)
end
temp.send(:'[]=', keys.last, 10)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question