[英]what is the difference between += and =+ in ruby?"
The += and =+ is not working as I would expect. + =和= +无法正常工作。 The following code outputs the correct value for @@num_things.
以下代码为@@ num_things输出正确的值。
class Thing
@@num_things = 0 # class variable
def initialize()
@@num_things += 1 # increment @@num_things
end
def value
@@num_things
end
end
t1 =Thing.new()
puts t1.value
t2 =Thing.new()
puts t2.value
t3 =Thing.new()
puts t3.value
The output is : 输出为:
1
2
3
However, if you invert the expression from += to be =+ now the output becomes 但是,如果将表达式从+ =反转为= +现在输出将变为
1
1
1
What am i missing? 我想念什么? I would expect the output to be the same in both cases once the value is called.
我希望一旦调用该值,两种情况下的输出将相同。
There's no such token as =+
; 没有
=+
这样的标记; it's actually two tokens: assignment followed by the unary +
operator; 它实际上是两个令牌:赋值后跟一元
+
运算符; the latter is essentially a no-op, so @@num_things =+ 1
is equivalent to @@num_things = 1
. 后者本质上是无操作的,因此
@@num_things =+ 1
等效于@@num_things = 1
。
Since there is a +=
token, the language parser will parse it as a single token. 由于存在
+=
标记,因此语言解析器会将其解析为单个标记。
(In the early formulations of BCPL which was the precursor to C, the modern -=
operator was written as =-
.) (在作为C的前体的BCPL的早期公式中,现代的
-=
运算符写为=-
。)
Here's why: 原因如下:
y += x
is the same as y = x + y
. y += x
与y = x + y
。 +=
works in Ruby like it does in so many other programming languages. +=
在Ruby中的工作方式与在许多其他编程语言中一样。
y =+ x
is the same as y = +x
is the same as y = x
. y =+ x
与y = +x
与y = x
相同。 Ruby sees =+
as two operators, not one. Ruby将
=+
视为两个运算符,而不是一个。 This also holds for negative values of x
, too. 这对于
x
负值也成立。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.