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: undefine
[1,2,4,5,4,7]
NoMethodError: undefine
The point here is that hash[1] doesn't exist (nil) when it first sees 1 in the array.
hash[1]
nil
1
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.
hash = Hash.new(0)
0