Bird
0
0

You want to update multiple characters in a Ruby string efficiently. Which approach best uses string mutability?

hard📝 Application Q15 of 15
Ruby - String Operations
You want to update multiple characters in a Ruby string efficiently. Which approach best uses string mutability?
str = "hello"
# Update 'e' and 'o' to 'a' and 'u'
Astr.freeze; str[1] = 'a'
Bstr = str.sub('e', 'a').sub('o', 'u')
Cstr = "hallu"
Dstr[1] = 'a'; str[4] = 'u'
Step-by-Step Solution
Solution:
  1. Step 1: Identify direct string mutation

    str[1] = 'a'; str[4] = 'u' changes characters by index directly, using mutability efficiently without creating new strings.
  2. Step 2: Compare other options

    str = str.sub('e', 'a').sub('o', 'u') creates new strings with sub; str = "hallu" assigns a new string; str.freeze; str[1] = 'a' freezes string then tries to change causing error.
  3. Final Answer:

    str[1] = 'a'; str[4] = 'u' -> Option D
  4. Quick Check:

    Direct index assignment updates string efficiently [OK]
Quick Trick: Change characters by index for efficient updates [OK]
Common Mistakes:
  • Using sub which creates new strings
  • Assigning new string instead of mutating
  • Freezing string before modification

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes