Module: Async::Enumerable::Methods::Predicates::Find
- Defined in:
- lib/async/enumerable/methods/predicates/find.rb
Class Method Summary collapse
Instance Method Summary collapse
-
#find(ifnone = nil) {|item| ... } ⇒ Object?
(also: #detect)
Returns first element that satisfies condition (parallel, early termination).
Class Method Details
.included(base) ⇒ Object
8 9 10 11 12 |
# File 'lib/async/enumerable/methods/predicates/find.rb', line 8 def self.included(base) base.include(::Enumerable) # Dependency base.include(Configurable) # Dependency for collection resolution base.include(ConcurrencyBounder) # Dependency end |
Instance Method Details
#find(ifnone = nil) {|item| ... } ⇒ Object? Also known as: detect
Note:
Returns the fastest completing match, not necessarily the first by position.
Due to parallel execution, whichever element completes evaluation first will be returned.
Use synchronous find if positional order matters.
Returns first element that satisfies condition (parallel, early termination).
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/async/enumerable/methods/predicates/find.rb', line 20 def find(ifnone = nil, &block) return super unless block_given? result = Concurrent::AtomicReference.new(nil) __async_enumerable_bounded_concurrency(early_termination: true) do || __async_enumerable_collection.each do |item| break unless result.get.nil? .async do if block.call(item) # Use compare_and_set to ensure only the first match wins if result.compare_and_set(nil, item) # Stop the barrier early when we find a match .stop end end end end end found = result.get if found.nil? && ifnone ifnone.call else found end end |