Skip to content

Commit

Permalink
Exit early in Enumerable#one?.
Browse files Browse the repository at this point in the history
If we found two elements that match the predicate we know that we are
going to return false, so we don't need to examine the remaining elements.
  • Loading branch information
tilman2 committed Mar 1, 2009
1 parent 1cc7471 commit 5aa1b24
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions kernel/common/enumerable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -503,13 +503,23 @@ def any?(&prc)
# [ nil, true, 99 ].one? #=> true

def one?(&prc)
times = 0
found_one = false
if block_given?
each { |o| times += 1 if yield(o) }
each do |o|
if yield(o)
return false if found_one
found_one = true
end
end
else
each { |o| times += 1 if o }
each do |o|
if o
return false if found_one
found_one = true
end
end
end
times == 1
found_one
end

##
Expand Down

0 comments on commit 5aa1b24

Please sign in to comment.