Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q4 of 15
Ruby - Regular Expressions
What will be the output of this Ruby code?
sentence = "Welcome to Ruby"
position = sentence =~ /Ruby/
puts position
AError
B0
Cnil
D11
Step-by-Step Solution
Solution:
  1. Step 1: Understand the =~ operator

    The operator returns the index of the first match of the regex pattern in the string.
  2. Step 2: Locate the pattern in the string

    "Ruby" starts at index 11 in "Welcome to Ruby" (counting from 0).
  3. Final Answer:

    11 -> Option D
  4. Quick Check:

    Check string indexing and pattern position [OK]
Quick Trick: =~ returns index of first match or nil [OK]
Common Mistakes:
  • Assuming index starts at 1 instead of 0
  • Expecting the operator to return true/false
  • Confusing =~ with match method

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes