dou*_*ack 9 ruby hash constructor
我在代码中遇到了意外(对我而言)的行为,所以我试图在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)
Rus*_*nov 23
Hash.new(0)设置任意键为默认值0,而{}套nil
h1 = Hash.new(0)
h1.default # => 0
h1[:a] += 1 # => 1
h2 = {}
h2.default # => nil
h2[:a] += 1 # => NoMethodError: undefined method `+' for nil:NilClass
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3805 次 |
| 最近记录: |