0
0
Rubyprogramming~5 mins

String concatenation and << in Ruby

Choose your learning style9 modes available
Introduction

We join pieces of text together to make longer messages or combine words. This helps us build sentences or data step by step.

When you want to add a greeting and a name to make a full message.
When you read parts of a sentence from different places and want to join them.
When you build a list of words or phrases into one string.
When you want to add more text to an existing message without creating a new one.
Syntax
Ruby
string1 + string2
string1 << string2

The + operator creates a new string by joining two strings.

The << operator adds the second string to the first one directly, changing the original string.

Examples
This uses + to join two strings into a new one.
Ruby
greeting = "Hello, " + "world!"
puts greeting
This uses << to add text to the existing string.
Ruby
greeting = "Hello, "
greeting << "world!"
puts greeting
Combines a variable and strings using +.
Ruby
name = "Alice"
message = "Hi " + name + "!"
puts message
Sample Program

This program first adds " morning" to "Good" using <<, then adds "!" using +. Finally, it prints the full message.

Ruby
message = "Good"
message << " morning"
message = message + "!"
puts message
OutputSuccess
Important Notes

Using + creates a new string and does not change the original string.

Using << changes the original string by adding more text to it.

For many additions, << is faster and uses less memory.

Summary

+ joins strings but makes a new one.

<< adds text to the existing string.

Use << when you want to build a string step by step.