Reputation: 5167
I have a hash h
:
h = {145=>1, 137=>2, 34=>3}
I want to convert it into an array of hashes of the form:
[{cid:145, qty:1}, {cid:137, qty:2}, {cid:34, qty:3}]
My first attempt a solution works for this example:
h.keys.zip(h.values).map { |cid, qty| {cid:cid, qty:qty} }
Evaluates to
[{:cid=>145, :qty=>1}, {:cid=>137, :qty=>2}, {:cid=>34, :qty=>3}]
My worry is that h.keys
and h.values
won't always align, since hashes aren't necessarily ordered.
How can I solve this problem with the guarantee that the keys of h
will be paired with their corresponding values?
Upvotes: 0
Views: 72