For accessing a nested value in the following hash:
y={"en"=>
{"slogan"=>"Sky",
"countries"=>{"AW"=>"Aruba", "AF"=>"Afghanistan"},
"op_modes"=>{"classic"=>{0=>"Alert", 10=>"Auto"}},
"reg"=>
{"headline"=>"Online",
"key1"=>"value1",
"key2"=>"value2",
"key3"=>"value3",
"key4"=>"value4",
"installation"=>
{"text1"=>
"'3.2 Tomorrow:'\n",
"gridtypes"=>{"tt"=>"TT", "tn-s"=>"TN-S"}}}}}
I have this (found the way in this post):
key = 'en.countries.AW'
ki = key.split('.')
fg = ki.inject(y) {|h, k| h[k]} # => "Aruba"
How can I assign value "x value"
when a key does not exist? How can I create a new key (any depth) with this value?
I tried something like this but there is an error:
key = 'en.countries.new_one'
if fg.nil?
ki.inject(y) do |h, k|
h[k] = "x value"
end
end
Update:
The answer of sawa helped me a lot but I did a little modification to reach unlimited levels (depth).
key = 'en.countries.new_one'
key.split(".").inject(y) do |h, k|
h.key?(k) ? h[k] : h[k] = {}
end