How to concatenate two strings with the << operator in Ruby

Overview

Concatenating strings or string concatenation means joining two or more strings together. In Ruby, we can use the plus + operator to do this, or we can use the double less than operator <<. In this shot, we will use the << operator.

Syntax

str1 << str2

Parameters

  • str1: one of the strings you want to concatenate.
  • str2: the second of the strings you want to concatenate.

Return value

The return value is a new string that is a concatenation of the specified strings.

Code example

In the code example below, we create strings and use the << operator to concatenate them.

# create strings
str1 = "Milk: "
str2 = "2 litres"
str3 = "Eggs: "
str4 = "12"
# concatenate strings
a = str1 << str2
b = str3 << str4
# print returned values
puts a
puts b

Free Resources