0

In this thread: there are many good examples of how to replace a key within a hash without changing the value.

This current question differs in that it is relating to a multi-dimensional hash. This may be trivial for those of you with more experience, but for a newbie rubyist it has been quite confusing!

Given:

{"2008"=>{"1" => {"ebook"=>"1"}}, "a"=>{"1" => {"man"=>"1", "distressed"=>"1"}}

Assuming I have "NEW_KEY", I would like to achieve:

{"2008"=>{"1" => {"ebook"=>"1"}}, "a"=>{"NEW_KEY" => {"man"=>"1", "distressed"=>"1"}}

This is part of a wider attempt to loop through the inner hashes to try to figure out the number of occurrences of a word.

In the above example I would like to set "2" as the key for "a" as "a" has the neighbours "man" and "distressed" one time.

Thanks in advance for any insights.

UPDATE:

Of course, being tired I had not clocked that you can go one layer deeper into the Hash and then the approach is the same as has been linked to in the other SO thread.

Out of interest life became much easier when someone suggested using Structs

7
  • what you are asking is simple. I think your question could use a little more clarification as to what you really want and why. I have a feeling your use case is a bit more complex than the question. Commented Jan 14, 2015 at 16:00
  • @engineersmnky Have tried to add some additional info. Hopefully it adds some context. Commented Jan 14, 2015 at 16:10
  • So your desired output would be {"2008"=>{"1" => {"ebook"=>"1"}}, "a"=>{"2" => {"man"=>"1", "distressed"=>"1"}}? If so what is the desired output for say {"2008"=>{"1" => {"ebook"=>"1"}}, "a"=>{"1" => {"man"=>"1", "distressed"=>"1"}, "2"=>{"woman" => "1", "happy" => "1"}}? Since a Hash can only have unique keys you cannot have "2" twice the second result will overwrite the first. Commented Jan 14, 2015 at 16:16
  • {"2008"=>{"1" => {"ebook"=>"1"}}, "a"=>{"2" => {"man"=>"1", "distressed"=>"1"}, "2"=>{"2" => {"woman" => "1", "happy" => "1"}} Commented Jan 14, 2015 at 16:22
  • @engineersmnky This is part of a map reduce job (this being part of the reducer). So the "top" level keys will all be uniq (top being "2008", "a", "2" in this instance.) So there should only be unique keys within each inner hash Commented Jan 14, 2015 at 16:25

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.