这有什么问题?
class Vec2 attr_accessor :x, :y # ... def += (v) @x += v.x @y += v.y return self end # ... end我一直无法在网上找到很多。 有人说这是因为+ =在ruby中完成了调用+然后=,他在开玩笑吧?
在有趣的情况下,他是对的,是否有一些解决方法(除了定义一个名为“add”的方法)?
What is wrong with this?
class Vec2 attr_accessor :x, :y # ... def += (v) @x += v.x @y += v.y return self end # ... endI've not been able to find much online. Someone said it is because += in ruby is done calling + and then =, he was kidding right?
In the amusing case he was right, is there some workaround (aside from defining a method called "add")?
最满意答案
有人说这是因为+ =在ruby中完成了调用+然后=,他在开玩笑吧?
不,他是对的(除了“calling =”有点不准确,因为=不是方法)。
有没有一些解决方法(除了定义一个名为“add”的方法)?
你的意思不是定义+而是以+=会改变变量而不是对象为由的事实?
你可以改变+来改变对象,然后返回self ,在这种情况下, v1 += v2将与v1 + v2相同,并会改变对象。 然而,我强烈建议反对,因为没有人会期望+变异(类似地,大多数有红宝书意识的人会希望+=重新分配变量而不改变对象,所以试图改变它可能完全不可取)。
除此之外,不,没有办法解决这个问题。
Someone said it is because += in ruby is done calling + and then =, he was kidding right?
No, he is right (except that "calling =" is a bit inaccurate as = is not a method).
is there some workaround (aside from defining a method called "add")?
You mean other than defining + and living with the fact that += will change the variable and not the object?
You could change + to mutate the object and then return self, in which case v1 += v2 would be the same as v1 + v2 and would mutate the object. However I'd strongly advise against that as no one would expect + to be mutating (similarly most ruby-literate people would expect += to reassign the variable and not mutate the object, so trying to change that might just be inadvisable altogether).
Other than that, no, there's no way to work around this.
更多推荐
发布评论