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

ste*_*ang 9 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 @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
Run Code Online (Sandbox Code Playgroud)

为什么它不起作用?有人可以解释@color跨多个Example$实例的实际行为是什么?

meg*_*gas 11

在Ruby模块中,类是对象,因此可以为它们设置实例变量.

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

Test.print_test #=> red
Run Code Online (Sandbox Code Playgroud)

你的错误是认为变量@color对于:

module SharedVar
  @color
end
Run Code Online (Sandbox Code Playgroud)

module SharedVar
  def show_color
    @color
  end
end
Run Code Online (Sandbox Code Playgroud)

不是.

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

自我指针的另一种解释.在第一个示例中,指针设置为模块对象SharedVar,因此键入@color将引用该对象,SharedVar并且与另一个对象没有任何关联.在第二个示例中,show_color只能在某个对象上调用该方法,即ex1.show_color,因此指针将指向ex1对象.所以在这种情况下,实例变量将引用ex1对象.