我已經定義了Person類(名稱,年齡)。我試圖在@age實例變量上重載+ =運算符,但我沒有管理。在這裏我的腳本嘗試:未能超載運算符+ =
class Person
def initialize(name, age)
@name = name
@age = age
end
def age+= (value)
@age += value
end
def to_s
return "I'm #{@name} and I'm #{@age} years old."
end
end
laurent = Person.new "Laurent", 32
puts laurent
laurent.age += 2
puts laurent
這我在終端得到了錯誤:
person.rb:8: syntax error, unexpected tOP_ASGN, expecting ';' or '\n'
def age+= (value)
^
person.rb:15: syntax error, unexpected keyword_end, expecting $end
那麼,什麼是錯的?
在此先感謝。對不起,如果這可能是一個太明顯的問題。
這是工作,謝謝:)。只是爲了我的文化:如何才能超負荷運營商只是年齡?這可以與幾個成員(年齡,身高,體重)一起工作嗎? – loloof64
你不能。你可以添加一個方法'grow_older(年)開始@age + =年底'例如改變年齡。 – detunized
好的。非常感謝:) – loloof64