Ruby 类 extend module 后,类变量的查询问题

spike76 · March 16, 2020 · Last by zhengpd replied at March 19, 2020 · 3522 hits

昨天遇到的一个奇怪的问题,一直搞不清楚原因。

module Foo
  @@foo = 'foo'
end

class A; extend Foo; end
p A.singleton_class.class_variables #=>显示[:@@foo]
p A.singleton_class.class_variable_get("@@foo") 
#报错: uninitialized class variable @@foo in #<Class:A> (NameError)  Did you mean?  @@foo

为什么 class_variables 都能看到@@foo变量,但class_variable_get却拿不到,而且错误信息中的 Did you mean? @@foo也说明内部确实有@@foo

将代码改成A include Foo后,A.singleton_class.class_variables返回空数组,但A.singleton_class.class_variable_get("@@foo")却能返回 foo

A.singleton_class.singleton_class.class_variable_get("@@foo")
Reply to ShowLew

居然行了,但是想不通原因

我在 irb 里尝试了一下,发现 2.6.5 和 2.7 结果不一样,

A.singleton_class.class_variables

这个在 2.7 里是空 []

Reply to miao

确实😅 。2.7 里修正了这个行为,只能通过A.singleton_class.singleton_class.class_variables来获取了

zhengpd in Demystify Ruby Class Variables Lookup mention this topic. 19 Mar 01:22

Ruby 2.7.0 修改了 A.singleton_class.class_variables 的逻辑。我针对类变量查找做了些研究,总结较长,单独发了一个帖子在 https://ruby-china.org/topics/39628

You need to Sign in before reply, if you don't have an account, please Sign up first.