Bird
0
0

You want to build a sentence step by step by appending words stored in an array words = ["I", "love", "Ruby"]. Which code snippet correctly uses to create the sentence with spaces between words?

hard📝 Application Q15 of 15
Ruby - String Operations
You want to build a sentence step by step by appending words stored in an array words = ["I", "love", "Ruby"]. Which code snippet correctly uses << to create the sentence with spaces between words?
Asentence = ""; words.each { |w| sentence + w + " " }; sentence.strip!
Bsentence = ""; words.each { |w| sentence = w + " " }; sentence.strip!
Csentence = ""; words.each { |w| sentence << w << " " }; sentence.strip!
Dsentence = ""; words.each { |w| sentence + w << " " }; sentence.strip!
Step-by-Step Solution
Solution:
  1. Step 1: Understand how to append words with spaces

    We want to add each word and a space to the same string sentence using << which modifies in place.
  2. Step 2: Analyze each option

    sentence = ""; words.each { |w| sentence + w + " " }; sentence.strip! computes a new concatenated string but doesn't assign it back.sentence = ""; words.each { |w| sentence = w + " " }; sentence.strip! overwrites sentence with the current word + space each time.sentence = ""; words.each { |w| sentence << w << " " }; sentence.strip! correctly chains << to append the word then the space in place.sentence = ""; words.each { |w| sentence + w << " " }; sentence.strip! creates and modifies a temporary string but discards the result.
  3. Final Answer:

    sentence = ""; words.each { |w| sentence << w << " " }; sentence.strip! -> Option C
  4. Quick Check:

    Use chained << to append multiple strings [OK]
Quick Trick: Chain << to append multiple strings efficiently [OK]
Common Mistakes:
  • Using + which creates new strings inside loop
  • Mixing + and << incorrectly
  • Forgetting to remove trailing space with strip!

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes