0
0
Rubyprogramming~5 mins

Why strings are mutable in Ruby

Choose your learning style9 modes available
Introduction

Strings in Ruby can be changed after they are created. This helps you easily update text without making a new copy every time.

When you want to build or change a message step by step.
When you need to update user input or data without creating new strings.
When you want to save memory by modifying the same string instead of making many copies.
Syntax
Ruby
string = "hello"
string[0] = "H"
puts string  # Outputs "Hello"
You can change parts of a string using indexes or methods like replace.
Mutability means the original string object changes, not a new one created.
Examples
Changes the first letter from 'c' to 'b', so it prints 'bat'.
Ruby
str = "cat"
str[0] = "b"
puts str
Replaces the whole string content with 'Hi'.
Ruby
greeting = "Hello"
greeting.replace("Hi")
puts greeting
Adds ' language' to the end of the string, showing how strings can grow.
Ruby
name = "Ruby"
name << " language"
puts name
Sample Program

This program changes parts of the string, replaces it completely, and adds more text, showing string mutability.

Ruby
word = "dog"
word[2] = "g"
puts word
word.replace("cat")
puts word
word << "s"
puts word
OutputSuccess
Important Notes

Mutability makes string operations faster and uses less memory.

Be careful when sharing strings between parts of your program, as changes affect all references.

Summary

Ruby strings can be changed after creation, which is called mutability.

This helps update text easily without making new strings every time.

You can change parts, replace, or add to strings directly.