开发者

ruby: accessing caller variables from declared obj instance

开发者 https://www.devze.com 2023-02-11 23:04 出处:网络
class X end class A def get_it开发者_C百科 puts @the_variable end end class B def init_it @the_variable = X.new
class X
end
class A
    def get_it开发者_C百科
      puts @the_variable
    end
end

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

In the above code I want methods of Class A to access the instance of X instantiated in B


Try using 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
0

精彩评论

暂无评论...
验证码 换一张
取 消