Ivan Novozhenets
Ivan Novozhenets

Reputation: 63

set ruby hash element value by array of keys

here is what i got:

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

hash structure and set of keys can vary.
i need to get

hash[:a][:b][0][:c] == new_val

Thanks!

Upvotes: 2

Views: 464

Answers (2)

sawa
sawa

Reputation: 168071

Similar to Andy's, but you can use Symbol#to_proc to shorten it.

hash = {:a => {:b => [{:c => :old_val}]}}
keys = [:a, :b, 0, :c]
new_val = 10
keys[0...-1].inject(hash, &:fetch)[keys.last] = new_val

Upvotes: 3

Andrew Haines
Andrew Haines

Reputation: 6644

You can use inject to traverse your nested structures:

hash = {:a => {:b => [{:c => "foo"}]}}
keys = [:a, :b, 0, :c]

keys.inject(hash) {|structure, key| structure[key]}
# => "foo"

So, you just need to modify this to do a set on the last key. Perhaps something like

last_key = keys.pop
# => :c

nested_hash = keys.inject(hash) {|structure, key| structure[key]}
# => {:c => "foo"}

nested_hash[last_key] = "bar"

hash
# => {:a => {:b => [{:c => "bar"}]}}

Upvotes: 6

Related Questions