简体   繁体   中英

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?

Try This.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM