Bird
0
0

Which Ruby code snippet correctly replaces only the first occurrence of 'bird' with 'fish' in the string "bird bird bird" using sub?

easy📝 Syntax Q3 of 15
Ruby - String Operations
Which Ruby code snippet correctly replaces only the first occurrence of 'bird' with 'fish' in the string "bird bird bird" using sub?
A"bird bird bird".gsub('bird', 'fish')
B"bird bird bird".sub('bird', 'fish')
C"bird bird bird".sub(/bird/, 'fish').gsub('bird', 'fish')
D"bird bird bird".gsub(/bird/, 'fish').sub('bird', 'fish')
Step-by-Step Solution
Solution:
  1. Step 1: Understand sub behavior

    sub replaces only the first occurrence of the pattern.
  2. Step 2: Analyze options

    "bird bird bird".sub('bird', 'fish') uses sub directly on the string to replace the first 'bird' with 'fish'. "bird bird bird".gsub('bird', 'fish') uses gsub which replaces all occurrences. Options C and D combine sub and gsub unnecessarily.
  3. Final Answer:

    "bird bird bird".sub('bird', 'fish') -> Option B
  4. Quick Check:

    Only first 'bird' replaced [OK]
Quick Trick: Use sub to replace first occurrence only [OK]
Common Mistakes:
  • Using gsub instead of sub to replace only first occurrence
  • Combining sub and gsub unnecessarily
  • Using regex without need

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes