Reputation: 393
How to access attr_accessor
's instance variable from a subclass?
class A
attr_accessor :somevar
@somevar = 123
puts @somevar
end
class B < A
def meth
puts @somevar
end
end
B.new.meth
puts nil
...
P.S. I can use ActiveSupport.
Upvotes: 1
Views: 289
Reputation: 15089
First, you do not have a instance of A to assign a value. Put an initialize method on A so while creating an instance of B, you can pass somevar value as a parameter to the new function:
class A
attr_accessor :somevar
def initialize(somevar)
@somevar = somevar
end
end
class B < A
def meth
puts @somevar
end
end
B.new('LOL').meth
Upvotes: 1
Reputation: 5508
You need to set the instance variable in an initialize method -- this gets called whenever a new class instance is created:
class A
attr_accessor :somevar
def initialize
@somevar = 123
end
end
Upvotes: 1