From c816bab14bcf6bcfcac7766817e7b8155e3b8525 Mon Sep 17 00:00:00 2001 From: joey schoblaska Date: Sat, 25 Jul 2009 17:33:50 -0500 Subject: [PATCH] added Array.uniq_by to core_ext --- activesupport/lib/active_support/core_ext/array.rb | 1 + .../lib/active_support/core_ext/array/uniq_by.rb | 14 ++++++++++++ activesupport/test/core_ext/array_ext_test.rb | 22 ++++++++++++++++++++ 3 files changed, 37 insertions(+), 0 deletions(-) create mode 100644 activesupport/lib/active_support/core_ext/array/uniq_by.rb diff --git a/activesupport/lib/active_support/core_ext/array.rb b/activesupport/lib/active_support/core_ext/array.rb index b583c75..aeac7a9 100644 --- a/activesupport/lib/active_support/core_ext/array.rb +++ b/activesupport/lib/active_support/core_ext/array.rb @@ -4,3 +4,4 @@ require 'active_support/core_ext/array/conversions' require 'active_support/core_ext/array/extract_options' require 'active_support/core_ext/array/grouping' require 'active_support/core_ext/array/random_access' +require 'active_support/core_ext/array/uniq_by' \ No newline at end of file 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 0000000..72d058e --- /dev/null +++ b/activesupport/lib/active_support/core_ext/array/uniq_by.rb @@ -0,0 +1,14 @@ +class Array + + # Select unique elements based on their response to a proc + def uniq_by(proc) + select{ |item| select{|i| proc.call(i) == proc.call(item)}.index(item) == 0 } + end + + # Select unique elements based on their response to a proc + def uniq_by!(proc) + uniq_by_items = uniq_by(proc) + reject!{|item| !uniq_by_items.include?(item)} + end + +end \ No newline at end of file diff --git a/activesupport/test/core_ext/array_ext_test.rb b/activesupport/test/core_ext/array_ext_test.rb index 24d3389..ab28a81 100644 --- a/activesupport/test/core_ext/array_ext_test.rb +++ b/activesupport/test/core_ext/array_ext_test.rb @@ -358,3 +358,25 @@ class ArrayWrapperTests < Test::Unit::TestCase assert_equal ["foo", "bar"], Array.wrap(FakeCollection.new) end end + +class ArrayUniqByTests < Test::Unit::TestCase + def test_uniq_by + array = [{:id => 1, :val => 1}, + {:id => 2, :val => 1}, + {:id => 3, :val => 2}, + {:id => 4, :val => 3}] + + assert_equal array.uniq_by(Proc.new {|a| a[:val]}).map{|a| a[:id]}, [1,3,4] + end + + def test_uniq_by_bang + array = [{:id => 1, :val => 1}, + {:id => 2, :val => 1}, + {:id => 3, :val => 2}, + {:id => 4, :val => 3}] + + array.uniq_by!(Proc.new {|a| a[:val]}) + + assert_equal array.map{|a| a[:id]}, [1,3,4] + end +end \ No newline at end of file -- 1.6.3.3