Theguild logo

The Guild — A Blog About Development and Geekery

Written & Filmed by Kabisa

Custom Array#uniq for ActiveRecord results

Ariejan de vroom

Ariejan de Vroom – 3 June 2011
83 words in about 1 minute

You may be aware of the uniq method in Ruby:

1
[1,2,3,4,4,6,2].uniq => [1,2,3,4,6]

This does not work for arrays of ActiveRecord objects, especially if you want uniqueness on a arbitrary property. Here’s a snippet that allows you to uniquify an Array using an arbitrary property:

1
Hash[*arrayname.map {|obj| [obj.name, obj]}.flatten].values

Basically you create a new Hash, using the unique value as the key and the actual object as value. Then you convert the Hash#values back to an Array.

Ariejan de vroom

Ariejan de Vroom

Software Engineer • CodeRetreat Facilitator • Ruby, Go and C Programmer • Electronics Apprentice

At Kabisa, privacy is of the greatest importance. We think it is important that the data our visitors leave behind is handled with care. For example, you will not find tracking cookies from third parties such as Facebook, Hotjar or Hubspot on our website. Only cookies from Google and Vimeo are used in order to improve the user experience of our visitors. These cookies also ensure that relevant advertisements are displayed. Read more about the use of cookies in our privacy statement.