method

uniq

v1_9_2_180 - Show latest stable - Class: Array
uniq()
public

Returns a new array by removing duplicate values in self.

a = [ "a", "a", "b", "b", "c" ]
a.uniq   #=> ["a", "b", "c"]
c = [ "a:def", "a:xyz", "b:abc", "b:xyz", "c:jkl" ]
c.uniq {|s| s[/^\w+/]}  #=> [ "a:def", "b:abc", "c:jkl" ]

2Notes

custom uniq method

bvida · Jan 25, 20102 thanks

Build hash from elements of your Array using attribute as key and the element as value and return values of Hash:

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

Pass a block

Vidmantas · Jan 14, 2013

While this example is not so obvious on first look what the block passed does, here's a small explanation:

when the block is passed to this function, the uniqueness is checked based on a value returned by that block.

For example if it's array of objects with "user_id" method, then this would be:

tasks.uniq{|t| t.user_id } # returns only tasks with unique user_id