0

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

4 Answers 4

4

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"}
#    ]
Sign up to request clarification or add additional context in comments.

Comments

1
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.

1 Comment

thankyou for your input as well. both solutions work great. and thank you for the advice on asking the question, i will keep that in mind next time
0
hash = array.map {|ary| Hash[[:category, :item].zip ary ]}

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.