Bird
Raised Fist0
Rubyprogramming~10 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What does the Ruby method scan do when used on a string?
easy
A. It counts the number of characters in the string.
B. It replaces all matches of a pattern with another string.
C. It finds all matches of a pattern and returns them in an array.
D. It converts the string to uppercase.

Solution

  1. Step 1: Understand the purpose of scan

    The scan method searches the string for all occurrences of a pattern.
  2. Step 2: Identify the return value of scan

    It returns an array containing all matched parts of the string.
  3. Final Answer:

    It finds all matches of a pattern and returns them in an array. -> Option C
  4. Quick Check:

    scan returns matches array [OK]
Hint: Remember: scan returns all matches as an array [OK]
Common Mistakes:
  • Confusing scan with gsub (replacement)
  • Thinking scan returns a count
  • Assuming scan modifies the original string
2. Which of the following is the correct syntax to find all digits in a string str using scan?
easy
A. str.scan(/d+)
B. str.scan("\\d+")
C. str.scan('\d+')
D. str.scan(/\d+/)

Solution

  1. Step 1: Recognize the correct regex syntax in Ruby

    Ruby uses forward slashes /pattern/ to denote regular expressions.
  2. Step 2: Identify the correct regex for digits

    \d+ matches one or more digits. The pattern must be inside slashes for regex.
  3. Final Answer:

    str.scan(/\d+/) -> Option D
  4. Quick Check:

    Regex in slashes with \d+ = str.scan(/\d+/) [OK]
Hint: Use /pattern/ for regex, not strings, in scan [OK]
Common Mistakes:
  • Using string quotes instead of regex slashes
  • Missing escape backslash in regex
  • Using incorrect regex delimiters
3. What is the output of the following Ruby code?
text = "cat bat rat"
matches = text.scan(/.at/)
puts matches.inspect
medium
A. ["at", "at", "at"]
B. ["cat", "bat", "rat"]
C. ["c", "b", "r"]
D. []

Solution

  1. Step 1: Understand the regex /.at/

    The dot . matches any single character, so .at matches any three-letter word ending with 'at'.
  2. Step 2: Apply scan on the string

    The string "cat bat rat" contains "cat", "bat", and "rat" which all match the pattern.
  3. Final Answer:

    ["cat", "bat", "rat"] -> Option B
  4. Quick Check:

    scan finds all 3-letter words ending with 'at' [OK]
Hint: Dot matches any char; scan returns all full matches [OK]
Common Mistakes:
  • Thinking dot matches zero or multiple chars
  • Expecting partial matches like 'at' only
  • Confusing scan output with string split
4. The following code is intended to find all words starting with 'a' in sentence. What is the error?
sentence = "apple banana apricot avocado"
words = sentence.scan("a\w+")
puts words.inspect
medium
A. The pattern should be a regex, not a string.
B. The pattern should use double backslashes.
C. The method scan does not work on strings.
D. The variable name 'words' is invalid.

Solution

  1. Step 1: Check the argument type for scan

    The scan method expects a regex pattern, not a plain string.
  2. Step 2: Identify correct regex usage

    The pattern should be written as /a\w+/ to match words starting with 'a'.
  3. Final Answer:

    The pattern should be a regex, not a string. -> Option A
  4. Quick Check:

    scan requires regex pattern, not string [OK]
Hint: Use /pattern/ for regex in scan, not string quotes [OK]
Common Mistakes:
  • Passing string instead of regex to scan
  • Misunderstanding backslash escaping
  • Assuming scan modifies the string
5. Given the string data = "log12 ID123, ID456, ID789", how can you use scan to extract only the numeric parts after each 'ID' (e.g., ["123", "456", "789"])?
hard
A. data.scan(/ID(\d+)/).flatten
B. data.scan(/\d+/)
C. data.scan(/ID\d+/)
D. data.scan(/(ID\d+)/)

Solution

  1. Step 1: Understand the pattern to extract numbers after 'ID'

    The regex /ID(\d+)/ matches 'ID' followed by digits, capturing only digits in parentheses. This ignores other digits like '12' in 'log12'.
  2. Step 2: Use scan and flatten the result

    scan returns an array of arrays for capture groups, so flatten converts it to a simple array of strings.
  3. Final Answer:

    data.scan(/ID(\d+)/).flatten -> Option A
  4. Quick Check:

    Capture group extracts digits, flatten simplifies array [OK]
Hint: Use capture groups and flatten to get inner matches [OK]
Common Mistakes:
  • Using data.scan(/\d+/) which grabs all digits including extras like '12' and '78'
  • Using scan without flatten, getting nested arrays
  • Matching full 'ID123' instead of just digits
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard