查看@mu is too short's answer to another question ,我尝试了一种变体:
def anagrams(list)
h = Hash.new{ [] }
list.each_with_object(h){ |el, h| h[el.downcase.chars.sort] <<= el }
end
anagrams(['cars', 'for', 'potatoes', 'racs', 'four','scar', 'creams', 'scream'])
(盲目地假设会有一个 <<=
运算符。)它有效,但是 Hash.new{[]}
根本不是惯用语——我还没有找到任何例子。有什么问题吗?
最佳答案
这样的代码不常用的原因是它没有将其返回值插入散列中,因此用户需要调用 Hash#[]= 将对象插入散列中(这就是你在这里重新做:hash[key] <<= val 只是 hash[key] = hash[key] << val) 的缩写
关于ruby - Hash.new{[]} - 它有什么问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9549702/