简体   繁体   中英

ruby how to make a hash with new keys, and values from an array

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

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"}
#    ]
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.

hash = arr.each_with_object({}){|elem, hsh|hsh[elem[0]] = elem[1]}
hash = array.map {|ary| Hash[[:category, :item].zip ary ]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM