tlehman
tlehman

Reputation: 5167

Converting hash to array of hashes order preserved?

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

Answers (1)

Zini
Zini

Reputation: 914

h = {145=>1, 137=>2, 34=>3}
h.map!{ |k, v| {:cid =>k, :qty => v} }

Upvotes: 1

Related Questions