提交 c7850388 编写于 作者: M Marc-Andre Lafortune

Make Enumerable#many? iterate only over what is necessary

上级 a96e824c
......@@ -95,9 +95,16 @@ def index_by
# Returns true if the enumerable has more than 1 element. Functionally equivalent to enum.to_a.size > 1.
# Can be called with a block too, much like any?, so people.many? { |p| p.age > 26 } returns true if more than 1 person is over 26.
def many?(&block)
size = block_given? ? count(&block) : to_a.size
size > 1
def many?
cnt = 0
if block_given?
any? do |element|
cnt += 1 if yield element
cnt > 1
end
else
any?{ (cnt += 1) > 1 }
end
end
# The negative of the Enumerable#include?. Returns true if the collection does not include the object.
......
......@@ -104,6 +104,13 @@ def test_many
assert_equal true, GenericEnumerable.new([ 1, 2, 2 ]).many? {|x| x > 1 }
end
def test_many_iterates_only_on_what_is_needed
infinity = 1.0/0.0
very_long_enum = 0..infinity
assert_equal true, very_long_enum.many?
assert_equal true, very_long_enum.many?{|x| x > 100}
end
def test_exclude?
assert_equal true, GenericEnumerable.new([ 1 ]).exclude?(2)
assert_equal false, GenericEnumerable.new([ 1 ]).exclude?(1)
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册