Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我有一个哈希 {:a => b} 并且我想向该键添加一个值并将其转换为保留前一个值的数组。
所以结果是 {:a => [b, c]}
有没有比遍历哈希更好的方法来做到这一点?
试试这个。
h = {a: b} h[:a] = ((a[:a].is_a? Array) ? a[:a] : [a[:a]]) << c
简单的解决方案是创建一个数组哈希:
h = {} h[:a] = [] h[:a].push(b) h[:a].push(c)
我的意思是:即使只有一个值,也要使用数组。这使得处理更容易。