rowyourboat
rowyourboat

Reputation: 341

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

Upvotes: 0

Views: 1303

Answers (4)

Sergio Belevskij
Sergio Belevskij

Reputation: 2957

hash = arr.each_with_object({}){|elem, hsh|hsh[elem[0]] = elem[1]}

Upvotes: 0

BroiSatse
BroiSatse

Reputation: 44725

hash = array.map {|ary| Hash[[:category, :item].zip ary ]}

Upvotes: 0

Stefan
Stefan

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

Simone Carletti
Simone Carletti

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

Related Questions