我想将多个值附加到 ruby 哈希中的同一个键。一直在用
tags.merge!({'xyz': 'abc'})
向散列添加新标签,但是还没有找到向同一个键添加多个值的方法。
例如:
tags = {'square': 'blue', 'rectangle': 'green, 'circle': 'yellow'}
我想为形状添加另一种颜色,使其看起来像:
tags = {'square': 'blue', 'rectangle': 'green, 'circle': ['yellow','red']}
我该怎么做?
最佳答案
您可以将 block 传递给 merge
并使用合并到重复键中的值做你想做的事:
tags = {square: 'blue', rectangle: 'green', circle: 'yellow'}
tags.merge!({ circle: 'red', square: 'red' }) do |key, oldval, newval|
if key == :circle
# Change to array and add the new value
(oldval.is_a?(Array) ? oldval : [oldval]) << newval
else
# Acts like default
newval
end
end
# => {:square=>"red", :rectangle=>"green", :circle=>["yellow", "red"]}
但是如果:circle
是一个数组甚至只有一个元素会更好。
关于ruby - 如何将值附加到 ruby hashtag 中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32701621/