문제

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.

도움이 되었습니까?

해결책

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

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top