访问一个常量 [英] Accessing a constant
本文介绍了访问一个常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么我不能从 A访问下面的 B,但可以从主环境访问?
Why can't I access 'B' in the following from 'A' but can from the main environment?
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不同),常量查找在词法范围内。我找到了一个很好的博客帖子并进行了解释。引用:
As to why it doesn't work, in Ruby 1.8 and 1.9.2+ (it was different in 1.9.1), constant lookup is lexically scoped. I found a good blog post with an explanation. To quote:
请注意,这些规则适用于常量定义以及查找。
在1.8和1.9.2中,在class_evaluated块中定义的常量将在封闭的词法范围内而不是在接收方
的范围内定义
。
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
也是如此。
这篇关于访问一个常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文