From 0361414ae328c10de8ed778e826d8244ba0aa63a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim=20and=20Mikel=20Lindsaar?= Date: Sun, 24 Jan 2010 23:28:52 +0100 Subject: Add uniq_by and uniq_by! to Array. --- activesupport/lib/active_support/core_ext/array.rb | 1 + .../lib/active_support/core_ext/array/uniq_by.rb | 17 +++++++++++++++++ 2 files changed, 18 insertions(+) create mode 100644 activesupport/lib/active_support/core_ext/array/uniq_by.rb (limited to 'activesupport/lib/active_support/core_ext') diff --git a/activesupport/lib/active_support/core_ext/array.rb b/activesupport/lib/active_support/core_ext/array.rb index b583c7533e..4688468a8f 100644 --- a/activesupport/lib/active_support/core_ext/array.rb +++ b/activesupport/lib/active_support/core_ext/array.rb @@ -1,5 +1,6 @@ require 'active_support/core_ext/array/wrap' require 'active_support/core_ext/array/access' +require 'active_support/core_ext/array/uniq_by' require 'active_support/core_ext/array/conversions' require 'active_support/core_ext/array/extract_options' require 'active_support/core_ext/array/grouping' diff --git a/activesupport/lib/active_support/core_ext/array/uniq_by.rb b/activesupport/lib/active_support/core_ext/array/uniq_by.rb new file mode 100644 index 0000000000..a09b2302fd --- /dev/null +++ b/activesupport/lib/active_support/core_ext/array/uniq_by.rb @@ -0,0 +1,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 -- cgit v1.2.3