微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

参见英文答案 > 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解析器故障.

原文地址:https://www.jb51.cc/ruby/265531.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐