从阵列和频率创建哈希 [英] Create hash from array and frequency
问题描述
我有一个数组 [1,2,4,5,4,7]
,我想找到每个号码的频率,并将其存储在一个哈希值。我有这个code,但它返回 NoMethodError:未定义的方法'+'的零:NilClass
高清得分(阵列)
散列= {}
array.each {|键|哈希[键] + = 1}
结束
所需的输出为
{1 = GT; 1,2 => 1,4 => 2,5 = GT; 1,7 => 1}
执行如下:
高清得分(阵列)
散列= Hash.new(0)
array.each {|键|哈希[键] + = 1}
哈希
结束
得分([1,2,4,5,4,7])#=> {1 =大于1,2 =大于1,4 =大于2,5 =大于1,7 =大于1}
或使用更Rubyish <一个href=\"http://www.ruby-doc.org/core-2.0.0/Enumerable.html#method-i-each_with_object\"><$c$c>Enumerable#each_with_object$c$c>:
高清得分(阵列)
array.each_with_object(Hash.new(0)){|键,哈希|哈希[键] + = 1}
结束
得分([1,2,4,5,4,7])#=&GT; {1 =大于1,2 =大于1,4 =大于2,5 =大于1,7 =大于1}
为什么
NoMethodError的原因:未定义的方法'+'的零:NilClass
块引用>
哈希= {}
是一个空的了,使用默认值无
。零
是Nilclass的实例
和NilClass
没有任何所谓的实例方法#+
。所以,你得到了NoMethodError
。看那
哈希::新
文档:新建→new_hash
新(OBJ)→new_hash
返回一个新的空哈希。的 <青霉>如果该散列随后由不对应于散列条目一键访问,则返回值取决于新的用于创建哈希的样式。在第一种形式,访问返回nil。如果指定物镜,这个单一对象将被用于所有的默认值。的如果指定一个块,则它会与哈希对象和键被调用,应当返回的默认值。它是该块的,如果需要存储在散列值的责任。
块引用>I have an array
[1,2,4,5,4,7]
and I want to find the frequency of each number and store it in a hash. I have this code, but it returnsNoMethodError: undefined method '+' for nil:NilClass
def score( array ) hash = {} array.each{|key| hash[key] += 1} end
Desired output is
{1 => 1, 2 => 1, 4 => 2, 5 => 1, 7 => 1 }
解决方案Do as below :
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}
Or more Rubyish using
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}
The reason of why
NoMethodError: undefined method '+' for nil:NilClass
?
hash = {}
is an empty has,with default value asnil
.nil
is an instance ofNilclass
,andNilClass
doesn't have any instance method called#+
. So you gotNoMethodError
.Look at the
Hash::new
documentation :new → new_hash new(obj) → new_hash
Returns a new, empty hash. If this hash is subsequently accessed by a key that doesn’t correspond to a hash entry, the value returned depends on the style of new used to create the hash. In the first form, the access returns nil. If obj is specified, this single object will be used for all default values. If a block is specified, it will be called with the hash object and the key, and should return the default value. It is the block’s responsibility to store the value in the hash if required.
这篇关于从阵列和频率创建哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!