ruby - 模块的实例变量是否在类与 mixin 之间共享?

标签 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

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

最佳答案

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

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

Test.print_test #=> red

你的错误是认为变量@color 是相同的:

module SharedVar
  @color
end

module SharedVar
  def show_color
    @color
  end
end

这不是。

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

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

关于ruby - 模块的实例变量是否在类与 mixin 之间共享?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9410921/

相关文章:

javascript - 设置最小变量

c++ - "using namespace"究竟做了什么?

ruby-on-rails - `method_missing' : undefined method `mail' for Emailer:Class (NoMethodError)

ruby-on-rails - 通过关联从具有多个关联中获取第一个关联

ruby-on-rails - 为什么参数包含有关 Controller 和操作的详细信息?

c++ - 从文件到变量?

ruby - 集合的性能 V.S. Ruby 中的数组

c - C 什么时候决定 char[] 是字符数组还是字符串?

c++ - 对变量范围感到困惑 - 意外调用析构函数

c - 从另一个文件访问的 C 中的静态变量