0
0
Rubyprogramming~3 mins

Why String concatenation and << in Ruby? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could glue words together instantly without rewriting your whole sentence every time?

The Scenario

Imagine you want to build a long sentence by adding one word at a time. You try to write each word separately and then join them manually, like gluing pieces of paper one by one.

The Problem

Doing this by hand is slow and messy. You might forget spaces, make typos, or waste time rewriting the whole sentence every time you add a new word.

The Solution

Using string concatenation and the << operator in Ruby lets you add words smoothly and quickly to your sentence without rewriting everything. It's like having a magic glue that sticks words together instantly.

Before vs After
Before
sentence = "Hello"
sentence = sentence + " world"
sentence = sentence + "!"
After
sentence = "Hello"
sentence << " world"
sentence << "!"
What It Enables

This makes building and changing sentences easy and fast, even when you have many parts to join.

Real Life Example

Think about creating a message for a chat app where users type words one by one. Using << helps you add each new word quickly without slowing down the app.

Key Takeaways

Manual string joining is slow and error-prone.

Using << adds text efficiently without rewriting.

It helps build long strings smoothly and clearly.