class Vartest_before
def init @instance_variable = “I belong to the instance”
end
attr_accessor :instance_variable
This defines a method instance_variable
def instance_variable @instance_variable = “Forced”
end
end
This defines the method instance_variable again. The version created by
attr_accessor doesn’t exist anymore.
end
This time it’s the other way around: First you define the method with
def, then you redefine it with attr_accessor. It’s like doing
def bla()
1
end
def bla()
2
end
Everytime you call bla, it will return 2 because the second definition
overrides the first one.
def instance_variable @instance_variable = “Forced”
b.init
I don’t understand what’s happening Can you ?
In the case of Vartest_before, when you call
puts b.instance_variable
the value of @instance_variable is changed to ‘Forced’ before being
returned.
If you substitute that line with
puts b.instance_variable_get(:@instance_variable)
you’d get what (I think) you expect, that is ‘Changed’. This doesn’t
happen
for the other class because there your definition of instance_variable
is
overwritten by the one provided by attr_accessor.