ruby:从声明的obj实例访问调用者变量

时间:2011-02-16 10:27:44

标签: ruby variables

class X
end
class A
    def get_it
      puts @the_variable
    end
end

class B
  def init_it
     @the_variable = X.new
     a = A.new
  end
end

在上面的代码中,我想要A类的方法来访问在B

中实例化的X实例

1 个答案:

答案 0 :(得分:2)

尝试使用Object#instance_variable_set

class B
  def init_it
     @the_variable = X.new
     a = A.new
     a.instance_variable_set(:@the_variable, @the_variable) 
 end
end