Ruby 模块的实例变量是否在类和mixin之间共享?

Ruby 模块的实例变量是否在类和mixin之间共享?,ruby,variables,scope,instance,mixins,Ruby,Variables,Scope,Instance,Mixins,我想知道Ruby模块的实例变量在多个类中是如何“混合”的。我编写了一个示例代码来测试它: # Here is a module I created with one instance variable and two instance methods. module SharedVar @color = 'red' def change_color(new_color) @color = new_color end def show_color puts @col

我想知道Ruby模块的实例变量在多个类中是如何“混合”的。我编写了一个示例代码来测试它:

# Here is a module I created with one instance variable and two instance methods.
module SharedVar
  @color = 'red'
  def change_color(new_color)
    @color = new_color
  end
  def show_color
    puts @color
  end
end

class Example1
  include SharedVar
  def initialize(name)
    @name     = name
  end
end

class Example2
  include SharedVar
  def initialize(name)
    @name     = name
  end
end

ex1 = Example1.new("Bicylops")
ex2 = Example2.new("Cool")

# There is neither output or complains about the following method call.
ex1.show_color
ex1.change_color('black')
ex2.show_color

为什么它不起作用?有人能解释一下,
@color
在多个
示例$
实例中的实际行为吗

您已将模块包含在类中。。因此实例变量@color应该是类Example1和Example2的实例变量

因此,如果您想访问@color变量,则意味着您假设为该类创建一个对象,然后您可以访问它

irb(main):028:0> ex1.change_color('black')
=> "black"
irb(main):029:0> ex1.show_color
black
irb(main):031:0> ex2.change_color('red')
=> "red"
irb(main):032:0> ex2.show_color
red

在Ruby中,模块和类都是对象,所以可以为它们设置实例变量

module Test
  @test = 'red'
  def self.print_test
    puts @test
  end
end

Test.print_test #=> red
您的错误是认为变量@color与以下内容相同:

module SharedVar
  @color
end

但事实并非如此

在第一个示例中,实例变量属于
SharedVar
对象,在第二个示例中,实例变量属于包含模块的对象


self指针的另一种解释。在第一个示例中,self指针设置为模块对象
SharedVar
,因此键入
@color
将引用对象
SharedVar
,并且与另一个对象没有连接。在第二个示例中,只能在某些对象上调用方法
show_color
,即
ex1.show_color
,因此self指针将指向
ex1
对象。因此,在本例中,实例变量将引用
ex1
对象。

这正是我正在做的。但是
ex1
ex2
都没有定义
color
。解释得很清楚!因此,如果我设计的模块是为了与其他类混合。我应该在
实例方法
中定义
实例变量
,我的理解正确吗?是的,只需计算当前自我,然后您就可以理解实例变量将放置在何处。谢谢。我现在只是在学习Ruby,而不是现在的自己。似乎比
javaScript
更优雅的语言。
module SharedVar
  def show_color
    @color
  end
end