Create hash from array and frequency

2019-03-16 07:07发布

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 }

标签: ruby arrays hash
7条回答
Root(大扎)
2楼-- · 2019-03-16 07:36

Or use the group by method:

arr = [1,2,4,5,4,7]

Hash[arr.group_by{|x|x}.map{|num,arr| [num, arr.size] }]
查看更多
登录 后发表回答