Ruby - String methods altering itself

Introduction

Ruby String class has many useful string-handling methods.

Most of these methods create new string objects.

In the following code, the s on the left side of the assignment on the second line is not the same object as the s on the right side:

Demo

s = "hello world" 
s = s + "!"

A few string methods can alter the string itself without creating a new object.

These methods generally end with an exclamation mark.

For example, the capitalize! method changes the original string, whereas the capitalize method does not.

The string itself is modified-and no new string is created-when you assign a character at an index of the string.

For example, s[1] = 'A' would place the character A at index 1 which is the second character of the string s.

You can check an object's identity using the object_id method.

Demo

s = "hello world" 
print( "1) s='#{s}' and s.object_id=#{s.object_id}\n" ) 
s = s + "!"            # this creates a new string object 
print( "2) s='#{s}' and s.object_id=#{s.object_id}\n" ) 
s = s.capitalize       # this creates a new string object 
print( "3) s='#{s}' and s.object_id=#{s.object_id}\n" ) 
s.capitalize!          # but this modifies the original string object 
print( "4) s='#{s}' and s.object_id=#{s.object_id}\n" ) 
s[1] = 'A'             # this also modifies the original string object 
print( "5) s='#{s}' and s.object_id=#{s.object_id}\n" )

Result

Related Topic