I’ve defined a Person class (name, age). I’ve tried to overload += operator on the @age instance variable, but I did not manage. Here my script attempt :
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
And this the error I’ve got in terminal :
person.rb:8: syntax error, unexpected tOP_ASGN, expecting ';' or '\n'
def age+= (value)
^
person.rb:15: syntax error, unexpected keyword_end, expecting $end
So, what’s wrong ?
Thanks in advance. And sorry if this may be a too obvious question.
You have to define
+operator instead and you get+=automatically.But in this case you don’t need to override the
+operator. Theagemember is just a number, so it already has everything defined. What you’re missing is aattr_accessor.You only need to override the
+operator in case you want your class to behave like a number and be able to add to it directly like this:But is not very readable in my opinion in this case.