Tag: 运算符重载

+ @是什么意思作为ruby中的方法

我正在阅读一些代码,我看到了一些类似的东西 module M def +@ self end end 我很惊讶这是合法的语法,但当我在文件上运行ruby -c (对于lint)时,它说它是有效的。 -@也是一个合法的方法名称,但当我尝试*@或d@ ,这些都是非法的。 我想知道+@是什么意思,为什么合法?

用于+ =的Ruby方法

有没有办法让Ruby能够做到这样的事情? class Plane @moved = 0 @x = 0 def x+=(v) # this is error @x += v @moved += 1 end def to_s “moved #{@moved} times, current x is #{@x}” end end plane = Plane.new plane.x += 5 plane.x += 10 puts plane.to_s # moved 2 times, current x is 15