0
0
Rubyprogramming~10 mins

Find/detect for first match in Ruby - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Find/detect for first match
Start with collection
Check each element
Does element match condition?
NoNext element
Yes
Return this element
End
The program checks each item in a list one by one until it finds the first item that meets the condition, then it stops and returns that item.
Execution Sample
Ruby
numbers = [3, 7, 10, 15]
result = numbers.find { |n| n > 8 }
puts result
This code finds the first number greater than 8 in the list and prints it.
Execution Table
StepCurrent Element (n)Condition (n > 8)Match?ActionResult
133 > 8 => falseNoCheck next elementnil
277 > 8 => falseNoCheck next elementnil
31010 > 8 => trueYesReturn 10 and stop10
4---Stop iteration10
💡 Iteration stops when element 10 matches condition n > 8.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
n-3710-
resultnilnilnil1010
Key Moments - 2 Insights
Why does the search stop after finding 10 and not continue to 15?
Because the find method returns the first element that matches the condition and stops immediately, as shown in execution_table step 3.
What happens if no element matches the condition?
The find method returns nil, meaning no matching element was found, as seen in steps 1 and 2 where no match occurs yet result stays nil.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'result' after step 2?
A3
B7
Cnil
D10
💡 Hint
Check the 'Result' column in execution_table row for step 2.
At which step does the condition n > 8 become true for the first time?
AStep 3
BStep 2
CStep 1
DStep 4
💡 Hint
Look at the 'Condition' and 'Match?' columns in execution_table.
If the array was [1, 2, 3], what would 'result' be after running the same code?
A1
Bnil
C3
DError
💡 Hint
Refer to key_moments explanation about no matching element returning nil.
Concept Snapshot
Use find (or detect) to get the first element matching a condition.
Syntax: collection.find { |item| condition }
Returns the first matching item or nil if none found.
Stops checking after first match.
Useful to quickly locate an element in a list.
Full Transcript
This example shows how Ruby's find method works. It looks at each element in the array one by one. For each element, it checks if the element is greater than 8. If not, it moves to the next element. When it finds the first element that is greater than 8, it returns that element and stops checking further. If no element matches, it returns nil. This helps to quickly find the first item that meets a condition without checking the whole list.