Custom Array#uniq for ActiveRecord results


Geschreven door ariejan op

You may be aware of the uniq method in Ruby:

[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:

Hash[* {|obj| [, 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.


  1. iain zegt:

    Actually, Ruby uses hashes under the cover when you call #uniq.

    And for making arrays uniq on arbitrary properties, use #uniq_by: collection.uniq_by(&:name). This should save you memory.

    Or, define the #== method on the objects, if you always uniq by the same property.

  2. Emiel Lohr zegt:

    Now with rails 3.2 you can use:

  3. In 1.9 you can use array.uniq(&:id)

  4. Rfqazfeg zegt:


Schrijf een reactie

Het e-mailadres wordt niet gepubliceerd. Verplichte velden zijn gemarkeerd met *

+ 2 = vier

RT @pixelambacht Working on getting the programme on the site, and reading all the talk topics. Gosh DARN this is going to be sweet!