为什么在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_modifies_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
的语法简写(其他<op>=
运算符也是如此),这是一个赋值.另一方面,<<
是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屋!