Create hash from array and frequency

前端 未结 8 1523
盖世英雄少女心
盖世英雄少女心 2021-02-05 21:23

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

8条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-05 21:54

    The point here is that hash[1] doesn't exist (nil) when it first sees 1 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.

提交回复
热议问题