我有一个数组[1,2,4,5,4,7]
,我想找到每个数字的频率并将其存储在哈希中。我有这个代码,但它返回NoMethodError: undefined method '+' for nil:NilClass
def score( array )
hash = {}
array.each{|key| hash[key] += 1}
end
所需的输出是
{1 => 1, 2 => 1, 4 => 2, 5 => 1, 7 => 1 }
在 Ruby 2.4+ 中:
def score(array)
array.group_by(&:itself).transform_values!(&:size)
end
执行以下操作:
def score( array )
hash = Hash.new(0)
array.each{|key| hash[key] += 1}
hash
end
score([1,2,4,5,4,7]) # => {1=>1, 2=>1, 4=>2, 5=>1, 7=>1}
或者更多 Rubyish 使用Enumerable#each_with_object
:
def score( array )
array.each_with_object(Hash.new(0)){|key,hash| hash[key] += 1}
end
score([1,2,4,5,4,7]) # => {1=>1, 2=>1, 4=>2, 5=>1, 7=>1}
为什么
NoMethodError: undefined method '+' for nil:NilClass
?
hash = {}
是一个空的 has,默认值为nil
. nil
是 的一个实例Nilclass
,并且NilClass
没有调用任何实例方法#+
。所以你得到了NoMethodError
.
查看Hash::new
文档:
new → new_hash
new(obj) → new_hash
返回一个新的空哈希。如果此哈希随后被不对应于哈希条目的键访问,则返回的值取决于用于创建哈希的 new 的样式。在第一种形式中,访问返回 nil。如果指定了 obj,则此单个对象将用于所有默认值。如果指定了一个块,它将使用散列对象和键调用,并且应该返回默认值。如果需要,将值存储在散列中是块的责任。
Ruby 2.7 及以后的版本将具有Enumerable#tally
解决此问题的方法。
从主干文档:
对集合进行计数。返回一个散列,其中键是元素,值是集合中与键对应的元素数。
["a", "b", "c", "b"].tally #=> {"a"=>1, "b"=>2, "c"=>1}
只需使用注入。这种类型的应用程序正是它的用途。就像是:
a.inject(Hash.new(0)) {|hash,word| hash[word] += 1; hash }
爱我一些注入:
results = array.inject(Hash.new(0)) {|hash, arr_element| hash[arr_element] += 1; hash }
1.9.3p448 :082 > array = [1,2,4,5,4,7]
=> [1, 2, 4, 5, 4, 7]
1.9.3p448 :083 > results = array.inject(Hash.new(0)) {|hash, arr_element| hash[arr_element] += 1; hash }
=> {1=>1, 2=>1, 4=>2, 5=>1, 7=>1}
这是一个使用哈希数组初始值设定项的简短选项
Hash[arr.uniq.map {|v| [v, arr.count(v)] }]
这里的要点是,当它第一次在数组中看到时,它hash[1]
不存在 ( )。nil
1
您需要以某种方式对其进行初始化,这hash = Hash.new(0)
是最简单的方法。0
是在这种情况下你想要的初始值。
或者使用 group by 方法:
arr = [1,2,4,5,4,7]
Hash[arr.group_by{|x|x}.map{|num,arr| [num, arr.size] }]