Alex Rivera | Logout

How to find an item in array which has the most occurrences

Asked 2009-01-05T02:51:56.163
58

How do I find an item in array which has the most occurrences?

[1, 1, 1, 2, 3].mode
=> 1

['cat', 'dog', 'snake', 'dog'].mode
=> dog
Edit
Report

1 Answer

3

if you are trying to avoid learning #inject (which you should not do...)

words = ['cat', 'dog', 'snake', 'dog']
count = Hash.new(0)

words.each {|word| count[word] += 1}
count.sort_by { |k,v| v }.last

but if I read this answer before, now I would know nothing about #inject and man, you need to know about #inject.

answered 2013-03-21T09:10:03.810

Your Answer