I know that instance variables have nothing to do with inheritance:
class A
def initialize
@x = 2
end
end
class B < A
def puts_x
puts @x
end
def x=(value)
@x = value
end
end
b = B.new
b.puts_x
b.x=3
b.puts_x
This outputs:
2
3
Here, class B inherits from class A, and @x in class B has nothing to do with inheritance.
But the output is 2. I want to understand it.
The "Ruby Inheritance" page says:
Since instance variables have nothing to do with inheritance, it follows that an instance variable used by a subclass cannot "shadow" an instance variable in the super-class. If a subclass uses an instance variable with the same name as a variable used by one of its ancestors, it will overwrite the value of its ancestor's variable.
I also want any examples for this.
B, you created a setter methodx=(value), and since you already inherited theinitializemethod from classAand initially set your instance variable@x = 2, when you calledb.x = 3, you called your setter method to change the value of that instance variable. So now@x = 3from there on for that instance ofb