gpt4 book ai didi

ruby - 模块中的 @ 和 @@ 有什么区别?

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

假设一个模块是包含的,而不是扩展的,那么模块实例变量和类变量有什么区别?

我看不出两者有什么区别。

module M
@foo = 1
def self.foo
@foo
end
end
p M.foo

module M
@@foo = 1
def self.foo
@@foo
end
end
p M.foo

我一直在模块中使用@作为@@,我最近看到其他代码在模块中使用@@。然后我想我可能一直在错误地使用它。

既然我们不能实例化一个模块,那么@和@@对于一个模块来说肯定没有区别。我错了吗?

-------------------- 添加了以下内容--------------------

为了回答关于评论和帖子的一些问题,我还测试了以下内容。

module M
@foo = 1
def self.bar
:bar
end

def baz
:baz
end
end

class C
include M
end

p [:M_instance_variabies, M.instance_variables] # [@foo]
p [:M_bar, M.bar] # :bar

c = C.new
p c.instance_variables
p [:c_instance_variabies, c.instance_variables] # []
p [:c_baz, c.baz] :baz
p [:c_bar, c.bar] # undefined method

当您在类中包含模块时,模块类变量和类方法不会在类中定义。

最佳答案

类变量可以在模块和包含这些模块的类之间共享。

module A
@@a = 5
end

class B
include A
puts @@a # => 5
end

同时,实例变量属于self。当您将模块 A 包含到类 B 中时,Aself 对象与 self 不同 B 的对象,因此您将无法在它们之间共享实例变量。

module A
@a = 5
end

class B
include A
puts @a # => nil
end

关于ruby - 模块中的 @ 和 @@ 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12358084/

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