String interpolation with #{} in Ruby - Time & Space Complexity
We want to understand how the time it takes to create a string with embedded values changes as the input grows.
How does the work increase when we add more parts inside the string?
Analyze the time complexity of the following code snippet.
names = ["Alice", "Bob", "Charlie", "Diana"]
result = ""
names.each do |name|
result += "Hello, #{name}! "
end
puts result
This code builds a greeting string by adding a message for each name in the list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over each name and concatenating a string (with interpolation) to the growing result using +=.
- Key detail: In Ruby, strings are mutable, but += creates a new string each time by copying the existing content plus the new part.
- How many times: n times, but each copy grows: lengths ~k for k=1 to n.
Each concatenation copies the accumulating string, so total work is sum of 1+2+...+n.
| Input Size (n) | Approx. Copy Operations |
|---|---|
| 10 | About 55 (1+2+...+10) |
| 100 | About 5,050 |
| 1000 | About 500,500 |
Pattern observation: The work increases quadratically with the number of names.
Time Complexity: O(n2)
This means the time to build the string grows quadratically as the number of names increases due to repeated copying of the growing string.
[X] Wrong: "Each string += operation is O(1) constant time."
[OK] Correct: Strings are mutable in Ruby, but += creates a new string by copying the entire existing content plus the addition, leading to quadratic total time.
Understanding how string building grows with input helps you write efficient code (e.g., use arrays and join) and explain your choices clearly.
"What if we used an array to collect all greetings first, then joined them once at the end? How would the time complexity change?"
Practice
#{} syntax do inside a double-quoted string in Ruby?Solution
Step 1: Understand string interpolation syntax
In Ruby,#{}inside double quotes allows inserting the value of Ruby expressions directly into the string.Step 2: Recognize the purpose of
This syntax evaluates the expression inside the braces and converts it to a string to include it in the larger string.#{}Final Answer:
It inserts the value of the expression inside the braces into the string. -> Option AQuick Check:
#{expression} inserts value [OK]
- Using #{ } inside single quotes expecting interpolation
- Thinking #{ } comments out code
- Confusing #{ } with variable declaration
name into a string?Solution
Step 1: Identify correct string quotes for interpolation
Ruby only processes#{}interpolation inside double-quoted strings, not single-quoted.Step 2: Check syntax correctness
"Hello, #{name}!" uses double quotes and#{name}correctly. 'Hello, #{name}!' uses single quotes, so no interpolation. "Hello, \#{name}!" escapes the #, so no interpolation. "Hello, #name!" misses braces, so no interpolation.Final Answer:
"Hello, #{name}!" -> Option CQuick Check:
Double quotes + #{variable} = interpolation [OK]
- Using single quotes which do not interpolate
- Escaping # which disables interpolation
- Omitting braces around variable
name = "Alice"
age = 30
puts "Name: #{name}, Age: #{age + 5}"Solution
Step 1: Evaluate expressions inside #{}
The variablenameis "Alice" andageis 30. The expressionage + 5evaluates to 35.Step 2: Construct the output string
The string becomes "Name: Alice, Age: 35" and is printed byputs.Final Answer:
Name: Alice, Age: 35 -> Option DQuick Check:
#{age + 5} calculates 35 [OK]
- Treating #{age + 5} as a string literal
- Not evaluating arithmetic inside interpolation
- Confusing output with raw code
count = 10
puts "You have #{count messages}"Solution
Step 1: Analyze the expression inside #{}
The expression inside interpolation iscount messageswhich is invalid syntax because Ruby expects a valid expression without spaces unless operators are used.Step 2: Understand correct usage
To concatenate or combine, you need an operator like + or string interpolation with proper syntax, e.g.,"#{count} messages".Final Answer:
Invalid expression inside #{}, spaces not allowed without operator -> Option AQuick Check:
#{expression} must be valid Ruby code [OK]
- Putting spaces without operators inside #{ }
- Forgetting to close #{ } properly
- Assuming interpolation works with invalid expressions
name = "Sam" current_year = Time.now.year # Choose the correct greeting message
Solution
Step 1: Check interpolation of variables
"Hello, #{name}! Welcome to #{current_year}." correctly uses double quotes and interpolates bothnameandcurrent_yearvariables.Step 2: Verify dynamic year calculation
"Hello, name! Welcome to #{Time.now.year}." usesTime.now.yearinside interpolation but misses interpolatingnameproperly (it's plain text). "Hello, #{name}! Welcome to current_year." treatscurrent_yearas plain text. 'Hello, #{name}! Welcome to #{current_year}.' uses single quotes, so no interpolation.Final Answer:
"Hello, #{name}! Welcome to #{current_year}." -> Option BQuick Check:
Double quotes + #{variable} for dynamic values [OK]
- Using single quotes which disable interpolation
- Not interpolating variables properly
- Confusing variable names with plain text
Ready to prove it?
Pass the test and this pattern moves unknown
