How to Concatenate Strings in Ruby

Contents
In this article, you will learn how to concatenate strings in Ruby.
How to concatenate strings
In Ruby, you can concatenate strings using the + operator or the << operator. Here are some examples:
Using the + operator
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
puts result
# Output: Hello World
In this example, we concatenate the strings str1 and str2 with a space in between using the + operator. The resulting string is stored in the result variable.
Using the << operator
str1 = "Hello"
str2 = "World"
str1 << " " << str2
puts str1
# Output: Hello World
In this example, we use the << operator to append the string str2 to the end of str1, separated by a space. The modified str1 is printed using puts.
Note that both methods modify the original string variables. If you want to concatenate strings without modifying the original variables, you can use string interpolation:
str1 = "Hello"
str2 = "World"
result = "#{str1} #{str2}"
puts result
# Output: Hello World
In this example, we use string interpolation to concatenate str1 and str2 with a space in between. The resulting string is stored in the result variable, and the output is printed using puts.