Bird
0
0

What is the output of the following Ruby code?

medium📝 Predict Output Q4 of 15
Ruby - String Operations
What is the output of the following Ruby code?
text = "foo bar foo bar"
result = text.sub('foo', 'baz')
puts result
Afoo bar foo bar
Bbaz bar foo bar
Cfoo bar baz bar
Dbaz bar baz bar
Step-by-Step Solution
Solution:
  1. Step 1: Understand sub behavior on the string

    sub replaces only the first occurrence of 'foo' with 'baz'.
  2. Step 2: Apply replacement to the string

    The first 'foo' becomes 'baz', the rest remains unchanged, so the string is "baz bar foo bar".
  3. Final Answer:

    baz bar foo bar -> Option B
  4. Quick Check:

    sub replaces first occurrence only = D [OK]
Quick Trick: sub changes only first match, leaves others intact [OK]
Common Mistakes:
  • Assuming all occurrences are replaced
  • Confusing sub with gsub
  • Misreading the string content

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes