14

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?

0

2 Answers 2

20

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"
Sign up to request clarification or add additional context in comments.

Comments

0

Building on sawa's answer, in modern Ruby with Hash#dig, this becomes even simpler:

    
*key, last = key.split(".")
    
h.dig(key)[last] = "b"
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.