ruby中的共享模块变量
我想知道是否可以在包含相同模块的类之间创建共享变量:ruby中的共享模块变量,ruby,Ruby,我想知道是否可以在包含相同模块的类之间创建共享变量: module Module1 @@shared class NestedClass1 def initialize @@shared = "hello world" end def foo p @@shared end end end module Module1 class NestedClass2 def bar p @@shared
module Module1
@@shared
class NestedClass1
def initialize
@@shared = "hello world"
end
def foo
p @@shared
end
end
end
module Module1
class NestedClass2
def bar
p @@shared
end
end
end
foo = Module1::NestedClass1.new
bar = Module1::NestedClass2.new
foo.bar
# => "hello world"
bar.bar
# => "hello world"
?您混淆了名称空间并包含模块。如果实际包含共享模块,并且实际初始化类变量,则可以共享类变量。如果不使用未定义的方法
NestedClass1 35; bar
,而是使用已定义的方法NestedClass1#foo
,则不会导致错误
module Module1
@@shared = nil
end
class NestedClass1
include Module1
def initialize
@@shared = "hello world"
end
def foo
p @@shared
end
end
class NestedClass2
include Module1
def bar
p @@shared
end
end
NestedClass1.new.foo # => "hello world"
NestedClass2.new.bar # => "hello world"
您的类不包含任何模块。@Nicolay,您的问题的答案是“是”,但有点不清楚您到底想做什么。您有要解决的特定问题吗?
@@shared
在顶部没有效果@@shared
是为Foo
定义的,因为它出现在initialize
中<代码>@@shared不是为条定义的。注意foo.class.class\u变量#=>[:@@shared]
,bar.class.class\u变量#=>[]
。啊,干杯!我想我把两者混淆了。有没有办法在同一名称空间内共享变量?例如,如果您正在编写一个gem,并且希望在不同的文件之间共享相同的变量?