如果它包含模块中变量的值,为什么我不能放置Ruby类的实例变量?

当我尝试运行此代码时,没有任何内容或nil显示。 我似乎无法理解为什么,因为我认为包含模块的类可以访问它的实例/类变量。 如果我不使用garbtest ,只需使用garbtest garb=方法为其分配不同的值,我就可以打印出这个值。 它工作正常而没有为它分配另一个值,因为我也将它初始化为16 。 有没有关于模块Test中的实例/类变量使它等于nil? 此外,当我尝试将@myg分配给@myg + @@vit它说nil类没有这样的方法。 我认为这进一步证实了我怀疑这些变量在某种程度上是nil 。 谢谢。

 module Test RED = "rose" BLUE = "ivy" @myg = 9 @@vit = 24.6 end class Xy include Test; def initialize(n) @garb = n end attr_accessor :garb; def garbTest @garb = @myg; end def exo return 50; end end ryu = Xy.new(16); ryu.garbTest; puts "#{ryu.garb}"; 

因为@myg不是共享变量。 它是模块Test私有属性,因此当你包含Test ,由于mixin@myg没有进入Xy ,默认情况下它也不会出现。 但是,“为什么没有?” – 因为,实例变量,类变量就是这样。 在初始化/定义它们之前,如果你试图使用它们,它只会给你nil

certificate自己和Ruby的小程序: –

 module Test @x = 10 @@y = 11 end class Foo include Test end Foo.instance_variable_defined?(:@x) # => false Test.instance_variable_defined?(:@x) # => true Foo.class_variable_defined?(:@@y) # => true Test.class_variable_defined?(:@@y) # => true 

您可以在Test singleton类中定义reader方法,然后就可以使用它。 往下看

 module Test class << self attr_reader :myg end RED = "rose" BLUE = "ivy" @myg = 9 @@vit = 24.6 end class Xy include Test def initialize(n) @garb = n end attr_accessor :garb def garbTest @garb = Test.myg end def exo return 50 end end ryu = Xy.new(16) ryu.garbTest # => 9