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

Community
  • 1
  • 1
dan-mi-sun
  • 551
  • 2
  • 4
  • 18
  • 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. – engineersmnky Jan 14 '15 at 16:00
  • @engineersmnky Have tried to add some additional info. Hopefully it adds some context. – dan-mi-sun Jan 14 '15 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. – engineersmnky Jan 14 '15 at 16:16
  • {"2008"=>{"1" => {"ebook"=>"1"}}, "a"=>{"2" => {"man"=>"1", "distressed"=>"1"}, "2"=>{"2" => {"woman" => "1", "happy" => "1"}} – dan-mi-sun Jan 14 '15 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 – dan-mi-sun Jan 14 '15 at 16:25
  • I think the reason this is still marked as a duplicate is that the dimensions of the hash don't make much difference. – J0e3gan Jan 14 '15 at 16:36
  • @J0e3gan thanks for that tip - had not realised it doesn't make a difference. Will continue trying out the applications in pry – dan-mi-sun Jan 14 '15 at 16:46

0 Answers0