0
0
Rubyprogramming~20 mins

Match operator (=~) in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Match Operator 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 =~?
Consider the following Ruby code snippet. What will it print?
Ruby
text = "hello world"
pattern = /world/
puts text =~ pattern
Anil
Btrue
C6
Dfalse
Attempts:
2 left
💡 Hint
The =~ operator returns the index of the first match or nil if no match.
Predict Output
intermediate
2: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
A0
B-1
Cfalse
Dnil
Attempts:
2 left
💡 Hint
If the pattern is not found, =~ returns nil.
🔧 Debug
advanced
2: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
ANoMethodError because nil does not support =~
BSyntaxError due to missing quotes
CReturns nil because no match
DReturns false because nil is falsey
Attempts:
2 left
💡 Hint
Only strings or objects that implement =~ can use it.
🧠 Conceptual
advanced
2: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/
A4
Bnil
C3
D0
Attempts:
2 left
💡 Hint
Count characters starting at 0 to find where "cad" starts.
Predict Output
expert
3: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}"
APosition: nil, Letters: abc
BPosition: 0, Letters: abc
CPosition: 0, Letters: nil
DPosition: 3, Letters: abc
Attempts:
2 left
💡 Hint
The =~ operator sets the global match variable $~ with named captures.