在 Ruby 中构建字符串时,为什么铲运算符 (<<) 比加等号 (+=) 更受欢迎? [英] Why is the shovel operator (<<) preferred over plus-equals (+=) when building a string in Ruby?
问题描述
我正在研究 Ruby Koans.
I am working through Ruby Koans.
about_strings.rb 中的 test_the_shovel_operator_modifying_the_original_string
Koan 包含以下注释:
The test_the_shovel_operator_modifies_the_original_string
Koan in about_strings.rb includes the following comment:
Ruby 程序员倾向于使用铲运算符 (<<) 而不是加号构建字符串时等于运算符 (+=).为什么?
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?
推荐答案
证明:
a = 'foo'
a.object_id #=> 2154889340
a << 'bar'
a.object_id #=> 2154889340
a += 'quux'
a.object_id #=> 2154742560
所以 <<
改变原始字符串而不是创建一个新字符串.这样做的原因是在 ruby 中 a += b
是 a = a + b
的语法简写(其他
运算符),这是一个赋值.另一方面,<<
是 concat()
的别名,它就地改变了接收者.
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.
这篇关于在 Ruby 中构建字符串时,为什么铲运算符 (<<) 比加等号 (+=) 更受欢迎?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!