我在代码中遇到了意外(对我而言)的行为,所以我试图在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
答案 0 :(得分:20)
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
答案 1 :(得分:0)
如果我们使用Hash.new(0)创建一个哈希对象,那么在这种情况下,参数0将被用作哈希的默认值 - 如果你查找一个不是的键,它将是返回的值但是在哈希
中def count_frequency(word_list)
counts = Hash.new(0)
word_list.each { |word|
counts[word] += 1
}
counts
end
p count_frequency(%w(red blue green red white black))
将产生
{"red"=>2, "blue"=>1, "green"=>1, "white"=>1, "black"=>1}
添加更多内容
brands= Hash.new( "nike" )
puts "#{brands[0]}"
puts "#{brands[101]}"
两者都会产生
nike
nike
和
brands = {0 => "nike" , 1 =>"Reebok"}
brands[0] # => "nike"
brands[1] # => "Reebok"
brands[100] # => nil