我可以在我的班级中实现+ =来增加包含值吗?

Vol*_*ort 2 ruby

考虑

class Container

  def initialize(value = 0)
    @value = value
  end

  def + (other)
    return @value + other
  end

  def - (other)
    return @value - other
  end

  def * (other)
    return @value * other
  end

  def / (other)
    return @value / other
  end

  def get
    return @value
  end

end
Run Code Online (Sandbox Code Playgroud)

我想+=用来增加容器中的值,如下所示:

c = Container.new(100)
c += 100
print c.get   # Expecting  200
Run Code Online (Sandbox Code Playgroud)

以上将无法正常工作,因为100将覆盖c.

我知道我可以使用像attr_accessora 这样的东西为这个值生成一个getter和setter,但是我很好奇我是否可以用更漂亮的方式来做这件事+=.

Ser*_*sev 10

既然c += 100只是糖c = c + 100,你就无法逃脱覆盖c.但是你可以用类似的对象覆盖它(而不是像你的问题中的fixnum).

class Container
  def initialize(value = 0)
    @value = value
  end

  def + (other)
    Container.new(@value + other)
  end

  def get
    @value
  end
end

c = Container.new(100)
c += 100
c.get # => 200
Run Code Online (Sandbox Code Playgroud)

  • 让`+`变异对象是一个非常糟糕的主意.`+`应返回一个增加值的新对象.你实现它的方式,写'd = c + 100`会改变`c`和`d`. (3认同)