Accessing a constant

后端 未结 4 1737
一个人的身影
一个人的身影 2021-01-18 12:33

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 #=> uninitial         


        
4条回答
  •  误落风尘
    2021-01-18 13:16

    The idiomatic way to do this would be

     A.const_set(:B, 1)
     A::B #=> 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:

    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.

    The same is also true for instance_eval.

提交回复
热议问题