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 }
Just use inject. This type of application is exactly what it is meant for. Something like:
The point here is that
hash[1]
doesn't exist (nil
) when it first sees1
in the array.You need to initialize it somehow, and
hash = Hash.new(0)
is the easiest way.0
is the initial value you want in this case.Here is a short option that uses the Hash array initializer
Do as below :
Or more Rubyish using
Enumerable#each_with_object
: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 :In Ruby 2.4+:
Love me some inject:
results = array.inject(Hash.new(0)) {|hash, arr_element| hash[arr_element] += 1; hash }