Introduction
Strings in Ruby can be changed after they are created. This helps you easily update text without making a new copy every time.
Strings in Ruby can be changed after they are created. This helps you easily update text without making a new copy every time.
string = "hello" string[0] = "H" puts string # Outputs "Hello"
replace.str = "cat" str[0] = "b" puts str
greeting = "Hello" greeting.replace("Hi") puts greeting
name = "Ruby" name << " language" puts name
This program changes parts of the string, replaces it completely, and adds more text, showing string mutability.
word = "dog" word[2] = "g" puts word word.replace("cat") puts word word << "s" puts word
Mutability makes string operations faster and uses less memory.
Be careful when sharing strings between parts of your program, as changes affect all references.
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.
str = "cat" str[1] = 'o' puts str
str = "dog" str.freeze str[0] = 'c' puts str
str = "hello" # Update 'e' and 'o' to 'a' and 'u'
Pass the test and this pattern moves unknown