seanberlin
seanberlin

Reputation: 171

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?

new_list = [

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

]

Upvotes: 1

Views: 840

Answers (1)

Aaron Christiansen
Aaron Christiansen

Reputation: 11807

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.

Upvotes: 3

Related Questions