我尝试了下面这段Ruby代码,以为会返回一个将单词长度映射到该长度的单词列表的哈希表,但实际上是空的。
map = Hash.new(Array.new)
strings = ["abc","def","four","five"]
strings.each do |word|
map[word.length] << word
end
然而,如果我将其修改为
map = Hash.new
strings = ["abc","def","four","five"]
strings.each do |word|
map[word.length] ||= []
map[word.length] << word
end
它确实起作用。
第一个版本只是创建一个默认值为空数组的哈希表吗?在这种情况下,我不明白为什么两个块会给出不同的值。
map = Hash.new {|h,k| h[k] = [] }
,它就能工作。 - Benjamin Tan Wei Hao