我已经定义了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