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
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.