Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set nested hash in ruby dynamically?

Tags:

ruby

hash

nested

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?

like image 470
Markus Avatar asked Jan 12 '13 15:01

Markus


1 Answers

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"
like image 137
sawa Avatar answered Sep 28 '22 08:09

sawa