Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a constant

Tags:

ruby

constants

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
like image 467
sawa Avatar asked Apr 09 '12 19:04

sawa


People also ask

What is a constant in access?

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.

How do you use a constant?

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.

How do you define a constant?

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.

What is the keyword for constant?

const valuesThe const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it.


2 Answers

Because . . .

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

like image 166
DigitalRoss Avatar answered Sep 25 '22 00:09

DigitalRoss


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
like image 32
Niklas B. Avatar answered Sep 24 '22 00:09

Niklas B.