Reputation: 341
I have an array of arrays like this:
arr = [["food", "eggs"],["beverage", "milk"],["desert", "cake"]]
And I need to turn it into an array of hashes where the keys are custom and new, and the values of the keys are the values in the array, like this:
hash = [{"category": "food", "item":"eggs"},
{"category": "beverage", "item":"milk"}
{"category": "desert", "item":"cake"}]
how would I do this? thank you
Upvotes: 0
Views: 1303
Reputation: 2957
hash = arr.each_with_object({}){|elem, hsh|hsh[elem[0]] = elem[1]}
Upvotes: 0
Reputation: 114248
Use Array#map
:
arr = [["food", "eggs"], ["beverage", "milk"], ["desert", "cake"]]
arr.map { |category, item| { category: category, item: item } }
# => [
# {:category=>"food", :item=>"eggs"},
# {:category=>"beverage", :item=>"milk"},
# {:category=>"desert", :item=>"cake"}
# ]
Upvotes: 4
Reputation: 176552
arr = [["food", "eggs"],["beverage", "milk"],["desert", "cake"]]
arr.inject([]) do |hash, (v1, v2)|
hash << { category: v1, item: v2 }
end
I used inject
to keep the code concise.
Next time you may want to show what you have tried in the question, just to demonstrate that you actually tried to do something before asking for code.
Upvotes: 1