Ruby + =重载(Ruby += overloading)

编程入门 行业动态 更新时间:2024-10-22 05:02:50
Ruby + =重载(Ruby += overloading)

这有什么问题?

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 # ... end

I'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.

更多推荐

本文发布于:2023-04-29 12:22:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1336370.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Ruby   overloading

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!