aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/core_ext/array
diff options
context:
space:
mode:
authorJosé Valim and Mikel Lindsaar <pair@programming.com>2010-01-24 23:28:52 +0100
committerJosé Valim and Mikel Lindsaar <pair@programming.com>2010-01-24 23:28:52 +0100
commit0361414ae328c10de8ed778e826d8244ba0aa63a (patch)
tree69dcc4b2c63c8e86d24e9ce84c14254e7c90e3ba /activesupport/lib/active_support/core_ext/array
parenta74a655648618a6ed568b9b4ef3a17a8970e7774 (diff)
downloadrails-0361414ae328c10de8ed778e826d8244ba0aa63a.tar.gz
rails-0361414ae328c10de8ed778e826d8244ba0aa63a.tar.bz2
rails-0361414ae328c10de8ed778e826d8244ba0aa63a.zip
Add uniq_by and uniq_by! to Array.
Diffstat (limited to 'activesupport/lib/active_support/core_ext/array')
-rw-r--r--activesupport/lib/active_support/core_ext/array/uniq_by.rb17
1 files changed, 17 insertions, 0 deletions
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