uniq() public

Returns a new array by removing duplicate values in self.

If a block is given, it will use the return value of the block for comparison.

It compares values using their #hash and #eql? methods for efficiency.

a = [ "a", "a", "b", "b", "c" ]
a.uniq   # => ["a", "b", "c"]

b = [["student","sam"], ["student","george"], ["teacher","matz"]]
b.uniq { |s| s.first } # => [["student", "sam"], ["teacher", "matz"]]
Show source
Register or log in to add new notes.
January 25, 2010
2 thanks

custom uniq method

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
January 14, 2013 - (>= v1_8_6_287)
0 thanks

Pass a block

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