Read more

Ruby: Find the most common string from an array

Arne Hartherz
March 29, 2012Software engineer at makandra GmbH

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"
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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.

Posted by Arne Hartherz to makandra dev (2012-03-29 15:56)