我想知道 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/