Bird
0
0

The following code is intended to replace all occurrences of 'apple' with 'orange' in the string, but it only replaces the first one. What is the error?

medium📝 Debug Q14 of 15
Ruby - String Operations
The following code is intended to replace all occurrences of 'apple' with 'orange' in the string, but it only replaces the first one. What is the error?
fruit = "apple banana apple grape"
new_fruit = fruit.sub('apple', 'orange')
puts new_fruit
AUse <code>gsub</code> instead of <code>sub</code> to replace all occurrences.
BThe string variable should be an array for replacement.
CThe replacement string must be in double quotes.
DThe method <code>sub</code> does not exist in Ruby.
Step-by-Step Solution
Solution:
  1. Step 1: Identify the method used

    The code uses sub, which replaces only the first match.
  2. Step 2: Correct method for replacing all matches

    To replace all occurrences, gsub should be used instead of sub.
  3. Final Answer:

    Use gsub instead of sub to replace all occurrences. -> Option A
  4. Quick Check:

    gsub replaces all matches, sub replaces first only [OK]
Quick Trick: Use gsub for all replacements, sub for first only [OK]
Common Mistakes:
  • Using sub when gsub is needed
  • Thinking sub works on arrays
  • Believing method names are case sensitive differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes