String Concatenation in Ruby

04 January 2015

String concatenation is most commonly used in all the applications, independent of programming languages. Let's take Ruby language.

Four Ways to Concatenate Strings in Ruby

Ruby provides several methods to concatenate strings:

1. Using the + Operator

str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
# => "Hello World"

2. Using String Interpolation

name = "Ruby"
result = "Welcome to #{name}"
# => "Welcome to Ruby"

3. Using the << Operator

str = "Hello"
str << " " << "World"
# => "Hello World"

4. Using the concat Method

str = "Hello"
str.concat(" World")
# => "Hello World"

Each method has its own use cases and performance characteristics. String interpolation is generally preferred for readability and performance.

← Back to Blog

About the Author

Kameshwaran Sachithanantham

Software Engineer cum Project Manager with 11+ years of experience in React, Node.js, React Native, and Ruby on Rails.