考虑
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
我想+=
用来增加容器中的值,如下所示:
c = Container.new(100)
c += 100
print c.get # Expecting 200
上面的方法不起作用,100
将覆盖它c
。
我知道我可以使用诸如之类的attr_accessor
方法为该值生成一个getter和setter方法,但是我很好奇我是否可以使用更漂亮的方法(例如using)来完成此操作+=
。
既然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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句