Modifying objects in place

How can I write a Foo.succ! method in my own class? When I try
def succ!() self = self.succ end
I get “Can’t change the value of self”

Tim Bates

···


tim@bates.id.au

“Tim Bates” tim@bates.id.au wrote in message
news:200211231746.11909.tim@bates.id.au…

How can I write a Foo.succ! method in my own class? When I try
def succ!() self = self.succ end
I get “Can’t change the value of self”

Tim Bates

tim@bates.id.au

self is a reference to the object(if the object is not of value-type). One
cannot change the reference.
You wish to change the the referenced value but not the reference itself.

class Foo
def initialize(v)
@a = v
end
def succ()
return @a.succ
end
def succ!()
@a = @a.succ
end
end

irb(main):042:0> var = Foo.new(4)
#<Foo:0x28d3d50 @a=4>
irb(main):043:0> var.succ
5
irb(main):042:0> var.succ!
5
irb(main):042:0> var
#<Foo:0x28d3d50 @a=5>