有没有办法使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

最佳答案

+=运算符与任何方法都没有关联,只是语法上的糖,当您编写a += b时,Ruby解释器将其转换为a = a + b,对于a.b += c而言,也将其转换为a.b = a.b + c。因此,您只需要根据需要定义x=x方法:

class Plane
  def initialize
    @moved = 0
    @x = 0
  end

  attr_reader :x
  def x=(x)
    @x = x
    @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

关于ruby - + =的Ruby方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16805933/

10-12 06:48