diff --git a/activesupport/CHANGELOG b/activesupport/CHANGELOG index 16d78e0201da5..0a4f2955680ba 100644 --- a/activesupport/CHANGELOG +++ b/activesupport/CHANGELOG @@ -1,5 +1,7 @@ *2.3.0/3.0* +* Added Enumerable#none? to check that none of the elements match the block #1408 [Damian Janowski] + * TimeZone offset tests: use current_period, to ensure TimeZone#utc_offset is up-to-date [Geoff Buesing] * Update bundled TZInfo to 0.3.12 [Geoff Buesing] diff --git a/activesupport/lib/active_support/core_ext/enumerable.rb b/activesupport/lib/active_support/core_ext/enumerable.rb index 788f3a7e9ead3..12659d7008149 100644 --- a/activesupport/lib/active_support/core_ext/enumerable.rb +++ b/activesupport/lib/active_support/core_ext/enumerable.rb @@ -104,4 +104,13 @@ def many?(&block) size = block_given? ? select(&block).size : self.size size > 1 end + + # Returns true if none of the elements match the given block. + # + # success = responses.none? {|r| r.status / 100 == 3 } + # + def none?(&block) + return true if !block_given? || blank? + !any?(&block) + end end diff --git a/activesupport/test/core_ext/enumerable_test.rb b/activesupport/test/core_ext/enumerable_test.rb index deb9b7544d1a3..288ce14b2cf6e 100644 --- a/activesupport/test/core_ext/enumerable_test.rb +++ b/activesupport/test/core_ext/enumerable_test.rb @@ -79,4 +79,14 @@ def test_many assert ![ 1, 2 ].many? {|x| x > 1 } assert [ 1, 2, 2 ].many? {|x| x > 1 } end + + def test_none + assert [].none? + assert [ 1 ].none? + + assert [].none? {|x| x > 1 } + assert ![ 2 ].none? {|x| x > 1 } + assert ![ 1, 2 ].none? {|x| x > 1 } + assert [ 1, 1 ].none? {|x| x > 1 } + end end