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

后端 未结 7 1002
一生所求
一生所求 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:54

    Proof:

    a = 'foo'
    a.object_id #=> 2154889340
    a << 'bar'
    a.object_id #=> 2154889340
    a += 'quux'
    a.object_id #=> 2154742560
    

    So << alters the original string rather than creating a new one. The reason for this is that in ruby a += b is syntactic shorthand for a = a + b (the same goes for the other = operators) which is an assignment. On the other hand << is an alias of concat() which alters the receiver in-place.

提交回复
热议问题