0
0
Rubyprogramming~10 mins

String concatenation and << in Ruby - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - String concatenation and <<
Start with string s = "Hello"
Use << to add " World"
s now "Hello World"
Use + to add "!"
s + "!" returns new string "Hello World!" but s unchanged
Print s and s + "!"
END
Start with a string, add more text using << which changes the original string, and + which creates a new string without changing the original.
Execution Sample
Ruby
s = "Hello"
s << " World"
puts s
puts s + "!"
This code adds " World" to s using <<, then prints s and s with "!" added using +.
Execution Table
StepCode executeds valueResult/Output
1s = "Hello""Hello"No output
2s << " World""Hello World"No output
3puts s"Hello World"Hello World
4puts s + "!""Hello World"Hello World!
💡 All code executed; s was mutated by << but not by +; program ends.
Variable Tracker
VariableStartAfter Step 2After Step 4 (final)
s"Hello""Hello World""Hello World"
Key Moments - 2 Insights
Why does s change after using << but not after using +?
Because << modifies the original string s (see Step 2 in execution_table), while + creates a new string without changing s (see Step 4).
What does puts s + "!" print if s is not changed?
It prints the new string "Hello World!" created by +, but s itself remains "Hello World" (see Step 4).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at Step 2, what is the value of s after s << " World"?
A" World"
B"Hello"
C"Hello World"
D"Hello World!"
💡 Hint
Check the 's value' column at Step 2 in execution_table.
At which step does the program output "Hello World!"?
AStep 2
BStep 4
CStep 3
DNo step outputs "Hello World!"
💡 Hint
Look at the 'Result/Output' column in execution_table for each step.
If we replaced s << " World" with s + " World", what would be the value of s after Step 2?
A"Hello"
B"Hello World"
C" World"
D"Hello World!"
💡 Hint
Refer to variable_tracker and remember + does not change s, it returns a new string.
Concept Snapshot
String concatenation in Ruby:
- << adds text to the original string (mutates it)
- + creates a new string without changing the original
- Use << to change the string in place
- Use + to combine strings without mutation
Full Transcript
This example starts with a string s set to "Hello". Using << adds " World" to s, changing s to "Hello World". When printing s, it shows "Hello World". Using + to add "!" creates a new string "Hello World!" but does not change s. Printing s + "!" shows "Hello World!" but s remains "Hello World". This shows << changes the original string, while + returns a new string without changing the original.