Add Enumerable#none?

This commit is contained in:
Jun Hiroe
2014-03-23 12:58:12 +09:00
parent ff6666632f
commit 1f709c1ef0
2 changed files with 31 additions and 0 deletions
+23
View File
@@ -413,4 +413,27 @@ module Enumerable
end
[min, max]
end
##
# call-seq:
# enum.none? [{ |obj| block }] -> true or false
#
# Passes each element of the collection to the given block. The method
# returns <code>true</code> if the block never returns <code>true</code>
# for all elements. If the block is not given, <code>none?</code> will return
# <code>true</code> only if none of the collection members is true.
#
# %w(ant bear cat).none? { |word| word.length == 5 } #=> true
# %w(ant bear cat).none? { |word| word.length >= 4 } #=> false
# [].none? #=> true
# [nil, false].none? #=> true
# [nil, true].none? #=> false
def none?(&block)
self.each do |val|
val = block.call(val) if block
return false if val
end
true
end
end
+8
View File
@@ -94,3 +94,11 @@ end
assert("Enumerable#minmax_by") do
assert_equal ["dog", "albatross"], %w(albatross dog horse).minmax_by { |x| x.length }
end
assert("Enumerable#none?") do
assert_true %w(ant bear cat).none? { |word| word.length == 5 }
assert_false %w(ant bear cat).none? { |word| word.length >= 4 }
assert_true [].none?
assert_true [nil, false].none?
assert_false [nil, true].none?
end