Bird
Raised Fist0
Rubyprogramming~10 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What does the Ruby operator =~ do when used like string =~ /pattern/?
easy
A. Splits the string into an array based on the pattern
B. Returns true if the pattern is found, false otherwise
C. Replaces the pattern in the string with another string
D. Returns the index where the pattern starts in the string or nil if not found

Solution

  1. Step 1: Understand the operator's purpose

    The =~ operator checks if a regex pattern matches anywhere in the string.
  2. Step 2: Know the return value

    It returns the index of the first match or nil if no match is found.
  3. Final Answer:

    Returns the index where the pattern starts in the string or nil if not found -> Option D
  4. Quick Check:

    =~ returns index or nil [OK]
Hint: Remember: =~ returns index or nil, not true/false [OK]
Common Mistakes:
  • Thinking it returns true or false
  • Confusing it with string replacement
  • Assuming it splits the string
2. Which of the following is the correct syntax to check if the string "hello123" contains digits using the match operator?
easy
A. "hello123" =~ /\d+/
B. "hello123" =~ "\d+"
C. "hello123" =~ /\w+/
D. "hello123" =~ /[a-z]+/i

Solution

  1. Step 1: Identify correct regex syntax

    The pattern to match digits is /\d+/, which is a regex literal in Ruby.
  2. Step 2: Match operator requires regex, not string

    The =~ operator expects a regex on the right side, so /\d+/ is correct, not a string.
  3. Final Answer:

    "hello123" =~ /\d+/ -> Option A
  4. Quick Check:

    Regex literal with =~ is correct [OK]
Hint: Use slashes /pattern/ for regex with =~ operator [OK]
Common Mistakes:
  • Using a string instead of regex on right side
  • Confusing \d with \w for digits
  • Missing regex delimiters
3. What will be the output of this Ruby code?
text = "OpenAI GPT-4"
index = text =~ /GPT/
puts index
medium
A. nil
B. 0
C. 7
D. SyntaxError

Solution

  1. Step 1: Locate the pattern in the string

    The string is "OpenAI GPT-4". The substring "GPT" starts at index 7 (counting from 0).
  2. Step 2: Understand what =~ returns

    The operator returns the index of the first match, so it returns 7.
  3. Final Answer:

    7 -> Option C
  4. Quick Check:

    Index of "GPT" in string = 7 [OK]
Hint: Count characters from zero to find match index [OK]
Common Mistakes:
  • Counting from 1 instead of 0
  • Expecting true/false instead of index
  • Assuming nil if unsure
4. Identify the error in this Ruby code snippet:
str = "test123"
result = str =~ "\d+"
puts result
medium
A. Using a string instead of a regex pattern with =~
B. Missing parentheses around =~ operator
C. Incorrect variable name 'str'
D. Using puts instead of print

Solution

  1. Step 1: Check the right side of =~ operator

    The code uses a string "\d+" instead of a regex literal /\d+/.
  2. Step 2: Understand =~ expects regex

    The match operator requires a regex pattern, so using a string causes a TypeError or unexpected behavior.
  3. Final Answer:

    Using a string instead of a regex pattern with =~ -> Option A
  4. Quick Check:

    Right side of =~ must be regex [OK]
Hint: Always use /pattern/ regex, not strings, with =~ [OK]
Common Mistakes:
  • Using strings instead of regex
  • Thinking parentheses are needed
  • Confusing puts with print
5. Given the array words = ["cat", "dog", "bird", "cow"], which code snippet uses the match operator to find the first word containing the letter 'i' and returns its index in the array?
hard
A. words.find { |w| w =~ /i/ }
B. words.find_index { |w| w =~ /i/ }
C. words.index { |w| w.include?('i') }
D. words.select { |w| w =~ /i/ }

Solution

  1. Step 1: Understand the goal

    We want the index of the first word containing 'i'.
  2. Step 2: Use find_index with match operator

    find_index returns the index of the first element where the block is true. Using w =~ /i/ returns index or nil, so truthy means match found.
  3. Step 3: Check other options

    words.index { |w| w.include?('i') } uses include? which works but is not using the match operator. words.find { |w| w =~ /i/ } returns the word, not index. words.select { |w| w =~ /i/ } returns all matches, not index.
  4. Final Answer:

    words.find_index { |w| w =~ /i/ } -> Option B
  5. Quick Check:

    find_index with =~ returns correct index [OK]
Hint: Use find_index with =~ to get index of first match [OK]
Common Mistakes:
  • Using find instead of find_index for index
  • Using include? instead of =~
  • Expecting select to return single index
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard