I am working through Ruby Koans.
The test_the_shovel_operator_modifies_the_original_string
Koan in about_strings.rb includes the follo
While a majority of answers cover +=
is slower because it creates a new copy, it's important to keep in mind that +=
and <<
are not interchangeable! You want to use each in different cases.
Using <<
will also alter any variables that are pointed to b
. Here we also mutate a
when we may not want to.
2.3.1 :001 > a = "hello"
=> "hello"
2.3.1 :002 > b = a
=> "hello"
2.3.1 :003 > b << " world"
=> "hello world"
2.3.1 :004 > a
=> "hello world"
Because +=
makes a new copy, it also leaves any variables that are pointing to it unchanged.
2.3.1 :001 > a = "hello"
=> "hello"
2.3.1 :002 > b = a
=> "hello"
2.3.1 :003 > b += " world"
=> "hello world"
2.3.1 :004 > a
=> "hello"
Understanding this distinction can save you a lot of headaches when you're dealing with loops!