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

ruby – 访问常量

发布时间:2020-12-16 23:09:25 所属栏目:百科 来源:网络整理
导读:为什么我不能从’A’访问以下’B’但可以从主环境访问? module A; endA.instance_eval{B=1}B #= 1A::B #= uninitialized 解决方法 这样做的惯用方法是 A.const_set(:B,1) A::B #= 1 至于为什么它不起作用,在Ruby 1.8和1.9.2中(它在1.9.1中有所不同),常量查
为什么我不能从’A’访问以下’B’但可以从主环境访问?
module A; end
A.instance_eval{B=1}

B #=> 1
A::B #=> uninitialized

解决方法

这样做的惯用方法是
A.const_set(:B,1)
 A::B #=> 1

至于为什么它不起作用,在Ruby 1.8和1.9.2中(它在1.9.1中有所不同),常量查找是词法范围的.我找到了一个很好的blog post解释.报价:

Note that these rules apply to constant definition as well as lookup.
In 1.8 and 1.9.2,a constant defined in a class_evaluated block will
be defined in the enclosing lexical scope,rather than the scope of
the receiver.

instance_eval也是如此.

(编辑:李大同)

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

    推荐文章
      热点阅读