BC00
BC00

Reputation: 1639

Ruby Hash Value into Array of Values

I have a hash {:a => b} and I want to add a value to that key and turn it into an array of values keeping the previous one.

So the result would be {:a => [b, c]}

Is there a better way to do this than iterating through the hash?

Upvotes: 0

Views: 114

Answers (2)

Abibullah Rahamathulah
Abibullah Rahamathulah

Reputation: 2891

Try This.

h = {a: b}
h[:a] = ((a[:a].is_a? Array) ? a[:a] : [a[:a]]) << c

Upvotes: 4

Benjamin M
Benjamin M

Reputation: 24567

Simple solution would be to create a Hash of Arrays:

h = {}
h[:a] = []
h[:a].push(b)
h[:a].push(c)

What I mean: Even if there's only one value use an array. That makes handling easier.

Upvotes: 0

Related Questions