Project1

标题: 不是很懂这个NameError [打印本页]

作者: 有丘直方    时间: 2018-9-8 21:46
标题: 不是很懂这个NameError

图中是2.5.1的Ruby的IRB
照道理说,class << Math的内部应该是Math模块的单例类,
在这个单例类中定义的实例方法内部,主调默认应该是Math这个模块
因此应该可以访问Math命名空间内的东西
但为啥Ruby在找PI这个常量的时候到#<Class:Math>找去了?
作者: fux2    时间: 2018-9-8 23:15
你都知道定义的实例方法了……Math的实例和Math模块不是一个玩意儿(x
越讲越怪,建议看源码。
作者: 百里_飞柳    时间: 2018-9-8 23:57
math模块里的类不包括模块的常量
改成Math::PI试试?
作者: RaidenInfinity    时间: 2018-9-9 00:17
本帖最后由 RaidenInfinity 于 2018-9-9 00:23 编辑

self::PI         
作者: shitake    时间: 2018-9-9 18:22
https://ruby-china.org/topics/28696
最后我想指出,你在一个class的singleton里是无法访问在class内定义的常量。

class A
  module B; end
end
class << A
  B
end
# NameError: uninitialized constant Class::B
这是因为singleton class的祖先链中并不包含自身的class,直接从Class开始。





欢迎光临 Project1 (https://rpg.blue/) Powered by Discuz! X3.1