Reputation: 1639
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
Reputation: 2891
Try This.
h = {a: b}
h[:a] = ((a[:a].is_a? Array) ? a[:a] : [a[:a]]) << c
Upvotes: 4
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