Ruby: Find the most common string from an array

Posted . Visible to the public.

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
Last edit
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2012-03-29 13:56)