Accessing a constant

后端 未结 4 1698
一个人的身影
一个人的身影 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:36

    From the documentation of instance_eval (emphasis mine):

    Evaluates a string containing Ruby source code, or the given block, within the context of the receiver (obj). In order to set the context, the variable self is set to obj while the code is executing, giving the code access to obj’s instance variables.

    Nothing more is done here. In particular, the constant assignment runs in the enclosing context of the block. Observe:

    irb(main):001:0> module A
    irb(main):002:1>   module B; end
    irb(main):003:1>   B.instance_eval { C = 1 }
    irb(main):004:1> end
    => 1
    irb(main):006:0> A::C
    => 1
    

提交回复
热议问题