Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top