gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 06:49:42 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com