Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么可以';如果Ruby类的实例变量包含模块中变量的值,我会放置它吗?_Ruby_Variables - Fatal编程技术网

为什么可以';如果Ruby类的实例变量包含模块中变量的值,我会放置它吗?

为什么可以';如果Ruby类的实例变量包含模块中变量的值,我会放置它吗?,ruby,variables,Ruby,Variables,当我尝试运行此代码时,没有显示任何内容或nil。我似乎不明白为什么,因为我认为包含模块的类可以访问其实例/类变量。如果我不使用garbtest并且只使用garb=方法为它指定一个不同的值,我可以很好地打印出该值。由于我也将其初始化为16,因此它工作正常,无需为其分配另一个值。模块测试中的实例/类变量是否使其等于nil?此外,当我试图将garb分配给@myg+@@vit时,它说nil类没有这样的方法。我认为这进一步证实了我的怀疑,即这些变量在某种程度上是nil。多谢各位 module Test

当我尝试运行此代码时,没有显示任何内容或
nil
。我似乎不明白为什么,因为我认为包含模块的类可以访问其实例/类变量。如果我不使用
garbtest
并且只使用
garb=
方法为它指定一个不同的值,我可以很好地打印出该值。由于我也将其初始化为
16
,因此它工作正常,无需为其分配另一个值。模块测试中的实例/类变量是否使其等于nil?此外,当我试图将
garb
分配给
@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
时,
@myg
由于混入而没有进入
Xy
,默认情况下它也不会出现。但是,“为什么是零?”-因为,实例变量,类变量都是这样的。在初始化/定义它们之前,如果您试图使用它们,它只会给您
nil

证明自己和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
模块测试
第9类

顺便说一句,在ruby中不需要以分号结尾。我知道。我刚从Java习惯了它。:)非常感谢。我不知道模块的实例变量也是私有的。不过,只有两个问题:为什么要将class@user3828080放在这里?我不知道模块的实例变量也是私有的——不仅是模块,而且对于类也是如此<代码>类这只是模块的默认行为吗?-它是硬编码的语言特性。你无法摆脱它。希望我能消除你的疑虑。