从阵列和频率创建哈希 [英] Create hash from array and frequency

查看:162
本文介绍了从阵列和频率创建哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组 [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:

 高清得分(阵列)
  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 returns NoMethodError: 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 as nil.nil is an instance of Nilclass,and NilClass doesn't have any instance method called #+. So you got NoMethodError.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆