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.
str1 << str2
str1
: one of the strings you want to concatenate.str2
: the second of the strings you want to concatenate.The return value is a new string that is a concatenation of the specified strings.
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
RELATED TAGS
CONTRIBUTOR
View all Courses