Bird
0
0

What is the main difference between sub and gsub methods in Ruby?

easy📝 Conceptual Q11 of 15
Ruby - String Operations
What is the main difference between sub and gsub methods in Ruby?
A<code>sub</code> replaces all matches, <code>gsub</code> replaces only the first match.
B<code>sub</code> replaces only the first match, <code>gsub</code> replaces all matches.
C<code>sub</code> deletes matches, <code>gsub</code> adds new text.
D<code>sub</code> works only on arrays, <code>gsub</code> works on strings.
Step-by-Step Solution
Solution:
  1. Step 1: Understand sub behavior

    sub replaces only the first occurrence of the pattern in the string.
  2. Step 2: Understand gsub behavior

    gsub replaces all occurrences of the pattern in the string.
  3. Final Answer:

    sub replaces only the first match, gsub replaces all matches. -> Option B
  4. Quick Check:

    sub = first match, gsub = all matches [OK]
Quick Trick: Remember: sub = single replace, gsub = global replace [OK]
Common Mistakes:
  • Confusing which method replaces all matches
  • Thinking sub works on arrays
  • Believing gsub replaces only one match

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes