Why is the shovel operator (<<) preferred over plus-equals (+=) when building a string in Ruby?

后端 未结 7 986
一生所求
一生所求 2020-11-28 18:17

I am working through Ruby Koans.

The test_the_shovel_operator_modifies_the_original_string Koan in about_strings.rb includes the follo

7条回答
  •  春和景丽
    2020-11-28 18:50

    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!

提交回复
热议问题