0
0
Rubyprogramming~20 mins

Scan for all matches in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Scan Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Ruby code using scan?

Consider the following Ruby code that uses scan to find all matches of digits in a string. What will be printed?

Ruby
text = "Order 123, item 456, code 789"
matches = text.scan(/\d+/)
puts matches.inspect
A["1", "2", "3", "4", "5", "6", "7", "8", "9"]
B[123, 456, 789]
C["123", "456", "789"]
Dnil
Attempts:
2 left
💡 Hint

Remember that scan returns an array of strings matching the pattern.

Predict Output
intermediate
2:00remaining
What does this scan with capture groups return?

Given this Ruby code, what is the output of p result?

Ruby
text = "Name: John, Age: 30; Name: Jane, Age: 25"
result = text.scan(/Name: (\w+), Age: (\d+)/)
p result
A[["John", "30"], ["Jane", "25"]]
B["John", "30", "Jane", "25"]
C["Name: John", "Age: 30", "Name: Jane", "Age: 25"]
D[]
Attempts:
2 left
💡 Hint

When scan uses capture groups, it returns an array of arrays with the captured parts.

🔧 Debug
advanced
2:00remaining
Why does this scan code raise an error?

Look at this Ruby code snippet. It raises an error. What is the cause?

Ruby
text = "abc123def456"
matches = text.scan(/(\d+)/).map(&:to_i)
puts matches
ANoMethodError because <code>to_i</code> cannot be called on an array
BNoMethodError because <code>map</code> is called on a string
CNo error; it prints [123, 456]
DNo error; it prints [["123"], ["456"]]
Attempts:
2 left
💡 Hint

Check what scan returns when there are capture groups and how map(&:to_i) works on the result.

📝 Syntax
advanced
2:00remaining
Which option correctly uses scan to find all words starting with 'a'?

Which Ruby code correctly finds all words starting with the letter 'a' in the string "apple banana apricot cherry"?

Ruby
text = "apple banana apricot cherry"
Atext.scan(/\b[a-z]+/)
Btext.scan(/a\w*/)
Ctext.scan(/\bA\w*/i)
Dtext.scan(/\ba\w*/)
Attempts:
2 left
💡 Hint

Use word boundary \b and match words starting with 'a'. Case sensitivity matters.

🚀 Application
expert
3:00remaining
Extract all email usernames from a string using scan

You have a string containing emails: "user1@example.com, admin@test.org, guest@domain.net". Which Ruby code extracts only the usernames (the part before '@') using scan?

Ruby
emails = "user1@example.com, admin@test.org, guest@domain.net"
Aemails.scan(/\w+@\w+\.\w+/)
Bemails.scan(/(\w+)@\w+\.\w+/).flatten
Cemails.scan(/(\w+@)/).map { |m| m[0].chomp('@') }
Demails.scan(/(\w+)@/)
Attempts:
2 left
💡 Hint

Use capture groups to get the username part before '@'. Flatten the result if needed.