Bird
0
0

What does the Ruby method sub do when called on a string?

easy📝 Conceptual Q1 of 15
Ruby - String Operations
What does the Ruby method sub do when called on a string?
ADeletes the pattern from the string
BReplaces all occurrences of a pattern in the string
CSplits the string at the pattern
DReplaces only the first occurrence of a pattern in the string
Step-by-Step Solution
Solution:
  1. Step 1: Understand the purpose of sub

    The sub method replaces only the first match of the pattern in the string.
  2. Step 2: Compare with other methods

    Unlike gsub, which replaces all matches, sub affects only the first occurrence.
  3. Final Answer:

    Replaces only the first occurrence of a pattern in the string -> Option D
  4. Quick Check:

    sub replaces first occurrence = C [OK]
Quick Trick: Use sub for first match, gsub for all matches [OK]
Common Mistakes:
MISTAKES
  • Thinking sub replaces all occurrences
  • Confusing sub with delete or split
  • Assuming sub modifies the original string

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes