加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 19:07:08 所属栏目:百科 来源:网络整理
导读:假设包含一个模块,而不是扩展,模块实例变量和类变量之间有什么区别? 我没有看到两者之间有任何区别. module M @foo = 1 def self.foo @foo endendp M.foomodule M @@foo = 1 def self.foo @@foo endendp M.foo 我一直在模块中使用@ as @@,我最近看到其他代
假设包含一个模块,而不是扩展,模块实例变量和类变量之间有什么区别?

我没有看到两者之间有任何区别.

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

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

由于我们无法实例化模块,因此模块的@和@@之间必须没有区别.我错了吗?

———————–添加以下内容——————–

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

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类中时,A的自身对象与B的自身对象不同,因此您将无法在它们之间共享实例变量.

module A
  @a = 5
end

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读