【发布时间】:2012-03-03 20:42:25
【问题描述】:
查看@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.new([])或Hash.new {|h, k| ... }。 -
@selman: 不,我的意思是块形式(没有 |h,k|),这就是重点。
-
你检查 rubyspecs 了吗?
-
@selman:
Hash.new([])也会产生令人惊讶的结果。 -
@NiklasB.:但是不同令人惊讶的结果。