我有一个像这样的数组:
arr = [["food", "eggs"],["beverage", "milk"],["desert", "cake"]]
我需要把它变成一个哈希数组,其中键是自定义的和新的,键的值是数组中的值,如下所示:
hash = [{"category": "food", "item":"eggs"},
{"category": "beverage", "item":"milk"}
{"category": "desert", "item":"cake"}]
我该怎么做? 谢谢
答案 0 :(得分:3)
使用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"}
# ]
答案 1 :(得分:1)
arr = [["food", "eggs"],["beverage", "milk"],["desert", "cake"]]
arr.inject([]) do |hash, (v1, v2)|
hash << { category: v1, item: v2 }
end
我使用inject
来保持代码简洁。
下次您可能想要在问题中展示您尝试过的内容,只是为了证明您在申请代码之前确实尝试过做某事。
答案 2 :(得分:0)
hash = arr.each_with_object({}){|elem, hsh|hsh[elem[0]] = elem[1]}
答案 3 :(得分:0)
hash = array.map {|ary| Hash[[:category, :item].zip ary ]}