Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

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

I am working through Ruby Koans.

The test_the_shovel_operator_modifies_the_original_string Koan in about_strings.rb includes the following comment:

Ruby programmers tend to favor the shovel operator (<<) over the plus equals operator (+=) when building up strings. Why?

My guess is it involves speed, but I don't understand the action under the hood that would cause the shovel operator to be faster.

Would someone be able to please explain the details behind this preference?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 <op>= operators) which is an assignment. On the other hand << is an alias of concat() which alters the receiver in-place.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...