I have a nested hash and I would like to rearrange the key/val pairs. The example below shows a hash of styles that points to hash of languages, which then points to a hash of the type of language it is. I want to reformat it to look like the new_hash example. I understand to structure it by iterating through the hash through different levels and creating the hash like that, however, the part I'm concerned/confused about is creating the array that :style points to and then pushing the correct style to it.
I assumed the code snippet would work as I expect it to. My new_hash will have a key of :language which points to another hash. This hash has a key of :style that points to an array in which I will store all the styles associated with each respective language. The :javascript hash should have two styles in its array since it exists twice in the original hash, however, when running this code snippet, the array is not adding both styles. It seems that during one iteration when assigning the hash, :javascript is assigned the style of :oo but in another iteration, it gets replaced with :functional. I'm not sure of the syntax to initialize the array and add multiple items to it while iterating through the hash.
hash = {
:oo => {
:ruby => {:type => "Interpreted"},
:javascript => {:type => "Interpreted"},
},
:functional => {
:scala => {:type => "Compiled"},
:javascript => {:type => "Interpreted"}
}
}
new_hash = {
:ruby => {
:type => "Interpreted", :style => [:oo]
},
:javascript => {
:type => "Interpreted", :style => [:oo, :functional]
},
:scala => {
:type => "Compiled", :style => [:functional]
}
}
hash.each do |style, programming_language|
programming_language.each do |language, type|
type.each do |key, value|
new_hash[language] = {:style => [style]}
end
end
end
hash. This is a good demonstration of why one should put the closing brace on its own line.