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

ruby – 动态添加的实例方法无法访问类变量

发布时间:2020-12-16 22:51:13 所属栏目:百科 来源:网络整理
导读:参见英文答案 Ruby looks for class variable in the Object instead of specific class1个 (问题已经在 Ruby Forum发布,但没有引起任何答案). 这是我的代码: class MC def initialize @x = 5 @@y = 6 end def f puts @x puts @@y endendm = MC.newm.f m.f
参见英文答案 > Ruby looks for class variable in the Object instead of specific class1个
(问题已经在 Ruby Forum发布,但没有引起任何答案).

这是我的代码:

class MC
  def initialize
    @x = 5
    @@y = 6
  end

  def f
    puts @x
    puts @@y
  end
end

m = MC.new
m.f

m.f产生预期的输出而没有错误:

5
6

但是这个:

def m.g
  puts @x
  puts @@y
end

m.g

生产:

5
warning: class variable access from toplevel
NameError: uninitialized class variable @@y in Object

为什么我可以从f访问@@ y,但不能从g访问?

在警告和错误消息中提及toplevel和Object令我感到困惑.

@x打印为5,因此其环境为MC.这排除了m.g定义中的@x和@@ y指向顶层环境(Object)而不是MC的可能性.

为什么我收到错误消息?

解决方法

以下所有变体均有效:
def m.g; puts self.class.send(:class_eval,'@@y') end

def m.g; puts self.class.class_variable_get(:@@y) end

class << m; def g; puts self.class.send(:class_eval,'@@y') end end

class << m; puts class_variable_get(:@@y) end

但这些失败了:

def m.g; puts @@y; end

class << m; puts class_eval('@@y') end

我认为这是一个ruby解析器故障.

(编辑:李大同)

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

    推荐文章
      热点阅读