0
0
Rubyprogramming~10 mins

Scan for all matches in Ruby - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Scan for all matches
Start with string
Apply scan method
Find all matches
Return array of matches
Use matches as needed
End
The scan method looks through the whole string and collects all parts that match a pattern, returning them as an array.
Execution Sample
Ruby
text = "I have 2 apples and 3 bananas"
numbers = text.scan(/\d+/)
puts numbers.inspect
This code finds all numbers in the text and prints them as an array.
Execution Table
StepActionPattern MatchedMatches FoundResult
1Start with string"I have 2 apples and 3 bananas"
2Apply scan with /\d+/\d+1["2"]
3Continue scan\d+2["2", "3"]
4No more matches["2", "3"]
5Return matches array["2", "3"]
💡 No more matches found, scan ends and returns array of all matches.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
text"I have 2 apples and 3 bananas""I have 2 apples and 3 bananas""I have 2 apples and 3 bananas""I have 2 apples and 3 bananas"
numbersnil["2"]["2", "3"]["2", "3"]
Key Moments - 2 Insights
Why does scan return an array even if only one match is found?
Because scan always collects all matches into an array, even if there is only one match, as shown in rows 2 and 3 of the execution_table.
What happens if the pattern matches nothing in the string?
Scan returns an empty array, since no matches are found. This is implied in the exit_note when no matches remain.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'numbers' after step 3?
A["2", "3"]
B["3"]
C["2"]
Dnil
💡 Hint
Check the 'Matches Found' and 'Result' columns at step 3 in the execution_table.
At which step does scan find the first match?
AStep 4
BStep 1
CStep 2
DStep 5
💡 Hint
Look at the 'Pattern Matched' and 'Matches Found' columns in the execution_table.
If the string had no digits, what would 'numbers' be after scan?
Anil
BAn empty array []
CArray with one empty string [""]
DThe original string
💡 Hint
Refer to the key_moments answer about what happens when no matches are found.
Concept Snapshot
Ruby's scan method searches a string for all parts matching a pattern.
It returns an array of all matches found.
If no matches, it returns an empty array.
Useful to extract multiple pieces like numbers or words.
Syntax: string.scan(/pattern/)
Example: "abc123".scan(/\d+/) => ["123"]
Full Transcript
This visual execution shows how Ruby's scan method works step-by-step. Starting with a string, scan looks for all parts matching a pattern. Each match is collected into an array. The example finds all numbers in the string "I have 2 apples and 3 bananas". First, it finds "2", then "3", and then stops when no more matches remain. The variable 'numbers' changes from nil to an array containing the matches. Scan always returns an array, even if only one match is found or none at all. This helps extract multiple pieces of information from text easily.