Reputation: 171
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
Reputation: 11807
I would probably:
map
to iterate over the elements in list
and build a new array at the same timenew_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