[英]what does this operator do in ruby? <<=
I have some code that I am debugging that uses this operator and I'm not sure why it is used. 我正在调试一些使用此运算符的代码,但不确定为什么要使用它。
It appears to be appending the object to an array. 它似乎是将对象附加到数组。 If that was all I do not know why the engineer didn't simply use the '<<' operator.
如果仅此而已,我不知道为什么工程师没有简单地使用'<<'运算符。 What is the difference?
有什么区别?
Thanks! 谢谢!
http://www.tutorialspoint.com/ruby/ruby_operators.htm http://www.tutorialspoint.com/ruby/ruby_operators.htm
it looks like its a bitwise left shift operation and assignment in one. 它看起来像是按位左移运算和分配的合二为一。
x <<= 2
is the same as 是相同的
x = x << 2
It is not always the case that <<
modifies the target: it might be the result that is of importance. <<
修改目标并非总是如此:可能是重要的结果。 Consult the API for the actual types used as to the behavior. 有关行为的实际类型,请查阅API。
A bit-shift of an integer does not have a side-effect (the computation is discarded unless it is assigned/used): 整数的移位没有副作用(除非分配/使用计算,否则将丢弃该计算):
a = 1
a << 2
a # => 1
a <<= 2
a # => 4
But <<
on an array does have a side-effect (and <<=
would just perform a useless assignment 1 that hides the side-effect nature of the operation): 但是数组上的
<<
确实有副作用(而<<=
只会执行一个无用的赋值1 ,从而隐藏了操作的副作用):
b = [1]
b << 2
b # => [1,2]
1 In rare cases, it might be "clever" with accessors to use obj.prop <<= val
for side-effecting operations as it will invoke both the getter and the setter - and the setter may contain logic. 1在极少数情况下,使用
obj.prop <<= val
进行副作用的操作可能会对访问器“很聪明”,因为它将同时调用getter和setter -并且setter可能包含逻辑。 However, I use the word "clever" and not "good" here for a reason :) 但是,出于某种原因,我在这里使用“聪明”一词而不是“好” :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.