How to Concatenate Strings in Ruby: Simple Syntax and Examples
In Ruby, you can concatenate strings using the
+ operator, the << method, or string interpolation with #{}. The + operator creates a new string, while << modifies the original string. String interpolation is a clean way to combine strings and variables.Syntax
Here are the main ways to concatenate strings in Ruby:
- Using
+operator: Joins two strings and returns a new string. - Using
<<method: Appends to the original string, modifying it. - Using string interpolation: Embeds variables or expressions inside a string with
#{}.
ruby
str1 = "Hello" str2 = "World" # Using + operator result_plus = str1 + " " + str2 # Using << method str1_dup = str1.dup str1_dup << " " << str2 # Using string interpolation result_interpolation = "#{str1} #{str2}"
Example
This example shows how to concatenate strings using all three methods and prints the results.
ruby
str1 = "Hello" str2 = "World" # Using + operator result_plus = str1 + " " + str2 puts "Using + : #{result_plus}" # Using << method str3 = "Hello" str3 << " " << str2 puts "Using << : #{str3}" # Using string interpolation result_interpolation = "#{str1} #{str2}" puts "Using interpolation : #{result_interpolation}"
Output
Using + : Hello World
Using << : Hello World
Using interpolation : Hello World
Common Pitfalls
Common mistakes when concatenating strings in Ruby include:
- Using
+operator repeatedly in a loop, which creates many temporary strings and slows down performance. - Modifying strings unintentionally with
<<, which changes the original string. - Forgetting to convert non-string values to strings before concatenation, causing errors.
Always ensure variables are strings or use interpolation which handles conversion automatically.
ruby
str = "Hello" # Wrong: modifies original string str << " World" puts str # Output: Hello World # If you want to keep original, use + str = "Hello" new_str = str + " World" puts str # Output: Hello puts new_str # Output: Hello World
Output
Hello World
Hello
Hello World
Quick Reference
| Method | Description | Modifies Original? | Example |
|---|---|---|---|
| + operator | Joins strings, returns new string | No | "Hello" + " World" => "Hello World" |
| << method | Appends to original string | Yes | "Hello" << " World" => "Hello World" (original changed) |
| String interpolation | Embeds variables inside strings | No | "#{var1} #{var2}" => combined string |
Key Takeaways
Use + to join strings without changing originals.
Use << to append and modify the original string efficiently.
String interpolation is the safest and cleanest way to combine strings and variables.
Avoid using + repeatedly in loops to prevent slow performance.
Always ensure non-string values are converted or use interpolation to avoid errors.