Ruby: Find the most common string from an array

This will give you the string that appears most often in an array:

names = %w[ foo foo bar bar bar baz ]
names.group_by(&:to_s).values.max_by(&:size).try(:first)
=> "bar"

This is very similar to the linked StackOverflow thread, but does not break on empty arrays.

Note that try is provided by ActiveSupport (Rails). You could explicitly load activesupport or use andand Show archive.org snapshot on plain Ruby.

Arne Hartherz About 12 years ago