< All Blog
November 13, 2022
In Ruby, it is prefered to use <<
(shovel operator) over +=
(plus operator) to modify strings.
The difference is that the shovel operator alter the original string, and plus operator creates a new instance.
In the following example, b
has a reference to a
, and when new string is appended to b
, the outcome is differe whether the original string (in this case, a
) is modified or not.
The shovel operator modifies the a
string instance, meaning a
and b
has the same object_id.
a = "a"
b = a
b << "b"
puts a #=> "ab"
puts a.object_id == b.object_id #=> true
The documentation for <<
is here:
Concatenates object to self and returns self: https://ruby-doc.org/core-3.1.2/String.html#method-i-3C-3C
It apparently says that it retrns self (not a new one).
On the other hands, the plus operator creates a new instance, meaning a
and b
has different object_id.
a = "a"
b = a
b += "b"
puts a #=> "a"
puts a.object_id == b.object_id #=> false
The documentation for +
is here:
Returns a new String containing other_string concatenated to self: https://ruby-doc.org/core-3.1.2/String.html#method-i-2B
It apparently says that it returns a new String.