【发布时间】:2012-03-13 17:35:05
【问题描述】:
我想知道 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 variables scope instance mixins