【发布时间】:2017-06-12 04:41:19
【问题描述】:
我的代码中出现了(对我而言)意外的行为,因此我尝试在 REPL 中隔离问题。然而,这些构造函数似乎都有相同的结果(一个空哈希):
irb> a = {}
# => {}
irb> b = Hash.new(0)
# => {}
当我将{} 传递给reduce 函数时,我得到了NoMethodError。这两个构造函数有什么区别?
irb> arr = "count the occurance of each of the words".scan(/\w+/)
# => ["count", "the", "occurance", "of", "each", "of", "the", "words"]
irb> x = arr.reduce(Hash.new(0)) { |hsh, word| hsh[word] += 1; hsh }
# => {"count"=>1, "the"=>2, "occurance"=>1, "of"=>2, "each"=>1, "words"=>1}
irb> x = arr.reduce({}) { |hsh, word| hsh[word] += 1; hsh }
# NoMethodError: undefined method `+' for nil:NilClass
【问题讨论】:
-
Documentation 不清楚吗? “如果指定了 obj,则这个单一对象将用于所有默认值。”
-
投反对票?这是一个合法的问题。我在 Ruby 上已经 3 天了(它是文档),不,我没有从文档中立即清楚地看到它。
-
即使有例子?
-
即便如此。实际上,早些时候我认为我错过了一些不言而喻的文档,但现在仔细观察,我看不到
{}构造函数模式在哪里被描述或与.new()进行比较。那是哪里?
标签: ruby hash constructor