aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/core_ext/array/uniq_by.rb
blob: a09b2302fd1c0180c5eac48cbc3bde8b6cf652e5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Array
  # Return an unique array based on the criteria given as a proc.
  #
  #   [1, 2, 3, 4].uniq_by { |i| i.odd? }
  #   #=> [1, 2]
  #
  def uniq_by
    hash, array = {}, []
    each { |i| hash[yield(i)] ||= (array << i) }
    array
  end

  # Same as uniq_by, but modifies self.
  def uniq_by!
    replace(uniq_by{ |i| yield(i) })
  end
end