String concatenation and << in Ruby - Time & Space Complexity
We want to understand how the time it takes to join strings grows as we add more pieces.
How does using different ways to combine strings affect the work done?
Analyze the time complexity of the following code snippet.
result = ""
strings = ["a", "b", "c", "d", "e"]
strings.each do |str|
result += str
end
puts result
This code joins many small strings into one big string using the + operator inside a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding strings together with
+=inside a loop. - How many times: Once for each string in the array.
Each time we add a string, the program copies the whole current result plus the new string.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 55 copies (1+2+...+10) |
| 100 | About 5050 copies |
| 1000 | About 500,500 copies |
Pattern observation: The work grows much faster than the number of strings; it grows roughly like the square of the input size.
Time Complexity: O(n²)
This means the time to join strings grows much faster as you add more strings, because each addition copies all the previous data.
[X] Wrong: "Adding strings with += inside a loop is always fast and grows linearly."
[OK] Correct: Each += creates a new string by copying the old one, so the work adds up more than just once per string.
Knowing how string joining works helps you write faster code and explain your choices clearly in real projects and interviews.
"What if we used << instead of += to join strings? How would the time complexity change?"
Practice
+ and << when used with strings in Ruby?Solution
Step 1: Understand
The+behavior+operator joins two strings but returns a new string without changing the original.Step 2: Understand
The<<behavior<<operator appends text directly to the original string, modifying it in place.Final Answer:
+creates a new string,<<modifies the original string. -> Option AQuick Check:
+new string,<<modifies original [OK]
+ new string, << changes original [OK]- Thinking
+changes the original string - Confusing
<<with creating a new string - Assuming both operators behave the same
greeting using << in Ruby?Solution
Step 1: Identify the correct operator for appending
In Ruby,<<is used to append text to an existing string variable.Step 2: Check syntax correctness
greeting << " world"correctly appends " world" togreeting. Other options are either invalid methods or use+which does not modify in place.Final Answer:
greeting << " world" -> Option DQuick Check:
Use<<to append text in place [OK]
<< to add text directly to string [OK]- Using
+which creates a new string - Trying to use non-existent methods like
add - Confusing method names like
appendwhich is not standard
str = "Hi" str << " there" puts str
Solution
Step 1: Analyze the initial string and operation
The variablestrstarts as "Hi". The<<operator appends " there" to it, modifyingstrto "Hi there".Step 2: Understand the output of
putsputs strprints the string with a newline, but the output shown is the string content without the newline character visible.Final Answer:
Hi there -> Option AQuick Check:
Appending with<<changes string to "Hi there" [OK]
<< adds text inside original string [OK]- Expecting
strto remain "Hi" - Confusing
putsoutput with return value - Thinking
<<causes an error
text = "Hello" text +<< " World" puts text
Solution
Step 1: Check the operator usage
The code uses+<<together, which is not a valid Ruby operator or syntax.Step 2: Understand Ruby syntax rules
Ruby does not allow chaining+and<<without spaces or parentheses; this causes a syntax error.Final Answer:
SyntaxError due to incorrect use of+<<-> Option BQuick Check:
Invalid operator+<<causes syntax error [OK]
+ and << cannot be combined directly [OK]- Assuming
+<<is valid syntax - Expecting
+to modify original string - Ignoring syntax errors from invalid operators
words = ["I", "love", "Ruby"]. Which code snippet correctly uses << to create the sentence with spaces between words?Solution
Step 1: Understand how to append words with spaces
We want to add each word and a space to the same stringsentenceusing<<which modifies in place.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!overwritessentencewith 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.Final Answer:
sentence = ""; words.each { |w| sentence << w << " " }; sentence.strip! -> Option CQuick Check:
Use chained<<to append multiple strings [OK]
<< to append multiple strings efficiently [OK]- Using
+which creates new strings inside loop - Mixing
+and<<incorrectly - Forgetting to remove trailing space with
strip!
Ready to prove it?
Pass the test and this pattern moves unknown
