有沒有辦法讓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
只需將您的方法重命名爲其他內容? – oldergod
是的,我想這樣..因爲+ =不能重載(我知道這只是現在)從http://stackoverflow.com/questions/3331962/list-of-ruby-operators-that-can-be-overloaded – Kokizzu
對類和它的實例使用相同的變量名「@ moved」和「@ x」是令人困惑的。 – sawa