Lets say I have a nested hash:
h = { 'one' =>
{'two' =>
{'three' => 'a'}
}
}
I can change it like this:
h['one']['two']['three'] = 'b'
How can I change the nested value with a variable as a key?
Let's say I have the following variable:
key = "one.two.three"
To access it dynamically, I use the following:
key.split('.').inject(h,:[])
But of course setting it like this does not work:
key.split('.').inject(h,:[]) = 'b' # fails
So how can I set the value of a nested hash dynamically?
Hash#[]=
is a single method. You cannot do Hash#[]
all the way to the last key and do =
to it. Rather, leave out the last key and do Hash#[]=
individually on it.
*key, last = key.split(".")
key.inject(h, :fetch)[last] = "b"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With