Bird
0
0

What will be the output of the following Ruby code?

medium📝 Predict Output Q4 of 15
Ruby - Regular Expressions
What will be the output of the following Ruby code?
text = "cat and dog"
match = text =~ /dog/
puts match
A3
B8
Cnil
D0
Step-by-Step Solution
Solution:
  1. Step 1: Understand the =~ operator

    The operator =~ returns the index of the first match or nil if no match.
  2. Step 2: Find the index of "dog" in the string

    In "cat and dog", 'd' in "dog" starts at index 8 (counting from 0).
  3. Final Answer:

    8 -> Option B
  4. Quick Check:

    Regex match index = 8 [OK]
Quick Trick: =~ returns match start index or nil if no match [OK]
Common Mistakes:
  • Assuming output is the matched string
  • Confusing index with length
  • Expecting nil when match exists

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes