< All Blog

Ruby: Shovel Operator or Plus Operator when Modifing String

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.

Example

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.

shovel operator

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).

plus operator

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.

Recommended Posts

  1. Ruby: Swap Variables in Oneline

    November 15, 2022
    In Ruby, there is a way to swap values of two different variables without using temporary variables. Let's say there are two variables that we'd like to swap. …
  2. Ruby: Array Brackets Operator Edge Cases

    November 14, 2022
    In Ruby, there is a [] (brackets) operator to access items in Array. https://ruby-doc.org/core-3.1.2/Array.html#method-i-5B-5D You can pass [start, length] to …