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

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.

Ariejan de Vroom

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