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
General. A constant represents a numeric or string value that doesn't change. Use constants to improve the readability of your Visual Basic code and to make your code easier to maintain.
You use the Const statement to declare a constant and set its value. By declaring a constant, you assign a meaningful name to a value. Once a constant is declared, it cannot be modified or assigned a new value. You declare a constant within a procedure or in the declarations section of a module, class, or structure.
A constant is a value that cannot be altered by the program during normal execution, i.e., the value is constant. When associated with an identifier, a constant is said to be “named,” although the terms “constant” and “named constant” are often used interchangeably.
const valuesThe const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it.
. . . constants that are not defined within a class or module are given global scope.
What matters for constant definition is the enclosing lexical scope, not the current receiver or the value of self
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With