Challenge - 5 Problems
Ruby Match Operator Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Ruby code using =~?
Consider the following Ruby code snippet. What will it print?
Ruby
text = "hello world" pattern = /world/ puts text =~ pattern
Attempts:
2 left
💡 Hint
The =~ operator returns the index of the first match or nil if no match.
✗ Incorrect
The string "hello world" contains "world" starting at index 6, so text =~ /world/ returns 6.
❓ Predict Output
intermediate2:00remaining
What does this =~ expression return when no match?
What is the output of this Ruby code?
Ruby
text = "goodbye" pattern = /hello/ puts text =~ pattern
Attempts:
2 left
💡 Hint
If the pattern is not found, =~ returns nil.
✗ Incorrect
Since "hello" is not in "goodbye", text =~ /hello/ returns nil.
🔧 Debug
advanced2:00remaining
Why does this =~ expression cause an error?
Look at this Ruby code. Why does it raise an error?
Ruby
text = nil pattern = /test/ puts text =~ pattern
Attempts:
2 left
💡 Hint
Only strings or objects that implement =~ can use it.
✗ Incorrect
Calling =~ on nil causes NoMethodError since nil does not have this method.
🧠 Conceptual
advanced2:00remaining
What is the value of 'index' after this code runs?
Given this Ruby code, what is the value of the variable index?
Ruby
index = "abracadabra" =~ /cad/
Attempts:
2 left
💡 Hint
Count characters starting at 0 to find where "cad" starts.
✗ Incorrect
"abracadabra" has "cad" starting at index 4, so index is 4.
❓ Predict Output
expert3:00remaining
What is the output of this complex =~ usage?
What does this Ruby code print?
Ruby
text = "123abc456" pattern = /\d{3}(?<letters>[a-z]{3})\d{3}/ match_pos = text =~ pattern letters = $~[:letters] puts "Position: #{match_pos}, Letters: #{letters}"
Attempts:
2 left
💡 Hint
The =~ operator sets the global match variable $~ with named captures.
✗ Incorrect
The pattern matches starting at index 0. The named group 'letters' captures "abc". So output is "Position: 0, Letters: abc".