我在代码中遇到了意外(对我而言)的行为,所以我试图在REPL中找出问题所在.但是,这些构造函数似乎都具有相同的结果(空哈希):
irb> a = {}
# => {}
irb> b = Hash.new(0)
# => {}
Run Code Online (Sandbox Code Playgroud)
当我{}进入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
Run Code Online (Sandbox Code Playgroud) 我正在阅读 ruby koans,但在理解何时运行此代码时遇到了一些麻烦:
hash = Hash.new {|hash, key| hash[key] = [] }
Run Code Online (Sandbox Code Playgroud)
如果散列中没有值,新数组何时分配给散列中的给定键?第一次访问哈希值而不先分配它时会发生这种情况吗?请帮助我了解何时为任何给定的哈希键创建了确切的默认值。