0
0
Rubyprogramming~20 mins

Common patterns and character classes in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Regex Mastery Badge
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 regex match?
Consider the following Ruby code snippet. What will be printed when it runs?
Ruby
text = "Email: user@example.com"
match = text.match(/\b\w+@\w+\.\w+\b/)
puts match[0]
AEmail
Bnil
Cexample.com
Duser@example.com
Attempts:
2 left
💡 Hint
Look for the pattern that matches an email-like string.
Predict Output
intermediate
2:00remaining
What does this regex find in the string?
Given the Ruby code below, what will be the output?
Ruby
text = "Call me at 123-456-7890 or 987-654-3210."
numbers = text.scan(/\d{3}-\d{3}-\d{4}/)
puts numbers.join(", ")
ACall, me, at
B1234567890, 9876543210
C123-456-7890, 987-654-3210
D[]
Attempts:
2 left
💡 Hint
Look for the pattern matching phone numbers with dashes.
🔧 Debug
advanced
2:30remaining
Why does this regex fail to match?
The following Ruby code is intended to find all words starting with a capital letter. Why does it not find any matches?
Ruby
text = "I."
matches = text.scan(/[A-Z][a-z]+/)
puts matches
AIt misses single-letter capital words like 'I' because the pattern requires at least one lowercase letter after the capital letter.
BThe regex is case-insensitive by default, so it matches everything.
CThe pattern uses wrong character classes; it should use \w instead of [a-z].
DThe scan method returns nil if no matches are found.
Attempts:
2 left
💡 Hint
Check what the pattern requires after the capital letter.
📝 Syntax
advanced
2:30remaining
Which regex pattern correctly matches a hexadecimal color code?
You want to match strings like '#1a2b3c' or '#ABCDEF' in Ruby. Which pattern is correct?
A/#([0-9a-fA-F]{6})\b/
B/#([0-9g-zA-Z]{6})/
C/#([0-9a-f]{6})/i
D/#([0-9a-fA-F]{3,6})/
Attempts:
2 left
💡 Hint
Hex digits are 0-9 and a-f (case insensitive).
🚀 Application
expert
3:00remaining
How many matches does this regex find?
In Ruby, given the string and regex below, how many matches will be found?
Ruby
text = "abc123xyz456def789"
matches = text.scan(/[a-z]+\d+/)
puts matches.size
A1
B3
C0
D2
Attempts:
2 left
💡 Hint
Look for sequences of letters followed immediately by digits.