开发者

ruby: accessing caller variables from declared obj instance

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜