0
0
Rubyprogramming~10 mins

Match operator (=~) in Ruby - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Match operator (=~)
Start
Evaluate left operand (string)
Evaluate right operand (regex)
Apply =~ operator
Check if regex matches string
Return index
End
The =~ operator checks if a regex matches a string and returns the index of the match or nil if no match.
Execution Sample
Ruby
text = "hello world"
result = text =~ /world/
puts result
This code checks if 'world' is in 'hello world' and prints the starting index of the match.
Execution Table
StepActionEvaluationResult
1Evaluate left operand"hello world""hello world"
2Evaluate right operand/world//world/
3Apply =~ operator"hello world" =~ /world/6
4Print resultputs 66
💡 Regex matches at index 6, so 6 is returned and printed.
Variable Tracker
VariableStartAfter Step 3Final
text"hello world""hello world""hello world"
resultnil66
Key Moments - 2 Insights
Why does the =~ operator return 6 instead of true?
The =~ operator returns the index where the match starts (6 here), not a boolean. See execution_table step 3.
What happens if the regex does not match the string?
The operator returns nil, meaning no match found. This is shown in the exit_note if no match occurs.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what is the result of applying =~?
A6
Btrue
Cnil
D0
💡 Hint
Check the 'Result' column in execution_table row for step 3.
At which step is the regex /world/ evaluated?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Action' column in execution_table to find when right operand is evaluated.
If the string was "hello" instead of "hello world", what would result be after step 3?
A6
B0
Cnil
Dtrue
💡 Hint
Recall that if regex does not match, =~ returns nil as explained in key_moments.
Concept Snapshot
Match operator (=~) in Ruby:
- Syntax: string =~ /regex/
- Returns index of match start if found
- Returns nil if no match
- Useful to check presence and position of pattern
- Not a boolean, but can be used in conditions
Full Transcript
The Ruby match operator =~ compares a string on the left with a regular expression on the right. It returns the index where the regex pattern starts in the string if it matches. If there is no match, it returns nil. For example, "hello world" =~ /world/ returns 6 because 'world' starts at index 6. This operator helps find if and where a pattern exists in text. It does not return true or false but an index or nil, which can be used in conditions to check matches.