Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding new keys to a Array Of Hashes

I have a collection of K:V Pairs as seen below:

list = [

{"Mary"=>"Die Hard"},
{"Paul"=>"The Grinch"},
{"John"=>"Halloween"},

]

But now I would like to flesh out and change the list, adding more specific keys in order to make it more searchable.

Is this possible or even an advisable way to go about this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

new_list = [

 { name: "Mary", film: "Die Hard"},
 { name: "Paul", film: "The Grinch"},
 { name: "John", film: "Halloween"},

]

>Solution :

I would probably:

  1. Use map to iterate over the elements in list and build a new array at the same time
  2. Since each element is a hash with one item, destruct that into a key and value
  3. Build the new hash in the correct format
new_list = list.map do |hash|
  # e.g. key = "Mary", value = "Die Hard"
  key, value = hash.first

  {name: key, film: value}
end

This assumes that each hash in the list will have only one item (as you’ve shown in your example in the question) – you may want to validate this elsewhere, since this solution would ignore any other items in the hash past the first.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading