From 992789d477500b86b38d760d06c0511fd15706f5 Mon Sep 17 00:00:00 2001 From: Ryan Orr Date: Sat, 19 Mar 2011 13:15:21 -0500 Subject: [PATCH] Checks for Enumerable content uniqueness --- .../lib/active_support/core_ext/enumerable.rb | 11 +++++++++++ activesupport/test/core_ext/enumerable_test.rb | 10 ++++++++++ 2 files changed, 21 insertions(+), 0 deletions(-) diff --git a/activesupport/lib/active_support/core_ext/enumerable.rb b/activesupport/lib/active_support/core_ext/enumerable.rb index 6d7f771..937ada1 100644 --- a/activesupport/lib/active_support/core_ext/enumerable.rb +++ b/activesupport/lib/active_support/core_ext/enumerable.rb @@ -100,6 +100,17 @@ module Enumerable size > 1 end + # Returns true if the collection has no duplicated content. + # Can be called with a block too, much like any?, so people.uniq? { |p| p.age > 26 } returns true if only 1 person is over 26. + def uniq?(&block) + if block_given? + collection = select(&block) + collection.uniq.size == collection.size + else + uniq.size == size + end + end + # The negative of the Enumerable#include?. Returns true if the collection does not include the object. def exclude?(object) !include?(object) diff --git a/activesupport/test/core_ext/enumerable_test.rb b/activesupport/test/core_ext/enumerable_test.rb index 4655bfe..d8aa67e 100644 --- a/activesupport/test/core_ext/enumerable_test.rb +++ b/activesupport/test/core_ext/enumerable_test.rb @@ -90,6 +90,16 @@ class EnumerableTests < Test::Unit::TestCase assert [ 1, 2, 2 ].many? {|x| x > 1 } end + def test_uniq + assert [].uniq? + assert [ 1 ].uniq? + assert [ 1, 2 ].uniq? + assert ![ 1, 1 ].uniq? + + assert [ 1, 1, 2 ].uniq? { |x| x > 1 } + assert ![ 1, 2, 2].uniq? { |x| x > 1 } + end + def test_exclude? assert [ 1 ].exclude?(2) assert ![ 1 ].exclude?(1) -- 1.7.4.1