diff --git a/activesupport/CHANGELOG b/activesupport/CHANGELOG index d87558aba93c47de18a5f2633ac6d112cf5eb029..4f61311d951e4562093416a88c53a14bc9b5e406 100644 --- a/activesupport/CHANGELOG +++ b/activesupport/CHANGELOG @@ -6,7 +6,7 @@ * Added Object#present? which is equivalent to !Object#blank? [DHH] -* Added Enumberable#many? to encapsulate collection.size > 1 [DHH] +* Added Enumberable#many? to encapsulate collection.size > 1 [DHH/Damian Janowski] * Add more standard Hash methods to ActiveSupport::OrderedHash [Steve Purcell] diff --git a/activesupport/lib/active_support/core_ext/enumerable.rb b/activesupport/lib/active_support/core_ext/enumerable.rb index 9647797ec2110e79cd113443ceb1eca76bfe2066..e451e9933afc81545cc069962889ad7ae3de491a 100644 --- a/activesupport/lib/active_support/core_ext/enumerable.rb +++ b/activesupport/lib/active_support/core_ext/enumerable.rb @@ -79,7 +79,9 @@ def index_by end # Returns true if the collection has more than 1 element. Functionally equivalent to collection.size > 1. - def many? + # Works with a block too ala any?, so people.many? { |p| p.age > 26 } # => returns true if more than 1 person is over 26. + def many?(&block) + size = block_given? ? select(&block).size : self.size size > 1 end end diff --git a/activesupport/test/core_ext/enumerable_test.rb b/activesupport/test/core_ext/enumerable_test.rb index fb9b9b8916f761d47169cb3f845d637d36682dbf..2315d8f3db438ab4c5002e074eec3fada6f727c2 100644 --- a/activesupport/test/core_ext/enumerable_test.rb +++ b/activesupport/test/core_ext/enumerable_test.rb @@ -63,10 +63,15 @@ def test_index_by assert_equal({ 5 => payments[0], 15 => payments[1], 10 => payments[2] }, payments.index_by { |p| p.price }) end - - def test_several + + def test_many assert ![].many? assert ![ 1 ].many? assert [ 1, 2 ].many? + + assert ![].many? {|x| x > 1 } + assert ![ 2 ].many? {|x| x > 1 } + assert ![ 1, 2 ].many? {|x| x > 1 } + assert [ 1, 2, 2 ].many? {|x| x > 1 } end end