The detect() of enumerable is an inbuilt method in Ruby returns the first element which satisfies the given condition in the block. If there is no block, then it returns the enumerator itself.
Ruby
Output:
Ruby
Output:
Syntax: block.detect { |obj| block } Parameters: The function takes the block according to which the first which satisfies is to be returned. Return Value: It returns the first element which satisfies the block or the enumerator instead.Example 1:
# Ruby program for detect method in Enumerable
# Initialize
enu = (1..50)
# returns first element
enu.detect { |el| el % 2 == 0 && el % 9 == 0}
18Example 2:
# Ruby program for detect method in Enumerable
# Initialize
enu = (1..50)
# returns enumerator
enu.detect
Enumerator: 1..50:detect