Ruby: Accessing class instance variables from one class in another class's class method

Mutuelinvestor picture Mutuelinvestor · Feb 19, 2011 · Viewed 7.7k times · Source

I am working on a ruby program and have run into the following problem.

I have two classes AClass and BClass as follows:

class AClass
  attr_accessor :avar
  def initialize(input)
    @avar = input
  end
end

class BClass
  def BClass.build(aclass)
    bvalue = aclass.avar
    ....
  end
end

When i run:

aclass = AClass.new           
puts aclass.avar              
bclass = BClass.build(aclass) 

The first two lines work fine. aclass is intialized and avar is put out to the screen, but the third line creates an error. I seems that the BClass build method can not access the AClass instance variable. What do I need to do to make this work. I thought the attr_accessor would enable me to access the AClass instance variables. Thanks in advance for your input.

Answer

Pan Thomakos picture Pan Thomakos · Feb 20, 2011

If you want to create a new type of initializer for BClass, you can do the following:

class AClass
  attr_accessor :avar

  def initialize(input)
    @avar = input
  end
end

class BClass
  attr_accessor :bvalue

  def self.build(aclass)
    bclass = self.new
    bclass.bvalue = aclass.avar
    bclass
  end
end

aclass = AClass.new 'ruby'
bclass = BClass.build aclass

This will set bclass.bvalue = aclass.avar = 'ruby'.