Reputation: 1728
Say I have:
class MyClass
MY_ENUM = [MY_VALUE_1 = 'value1', MY_VALUE_2 = 'value2']
end
Something like this is possible:
p MyClass::MY_VALUE_1 #=> "value1"
Why? Isn't MY_VALUE1
and MY_VALUE_2
constant scope inside the []
?
Upvotes: 4
Views: 478
Reputation: 67850
An array literal ([...]
) defines no scope. You seem to want a hash:
class MyClass
MY_ENUM = {:MY_VALUE_1 => "value1", :MY_VALUE_2 => "value2"}
end
MyClass::MY_ENUM[:MY_VALUE_1] #> value1
Upvotes: 2
Reputation: 107959
You can access the nested constant MY_VALUE_1
because it is in the same scope as the outer constant MY_ENUM
: Both constants are in the scope of class MyClass
.
You expected the [...]
construct to define a new scope, but it does not. In Ruby, only three things define a new scope:
class SomeName
module SomeName
def some_name
Upvotes: 4
Reputation: 692
If you want to prevent visibility outside the class (hiding) you can use 'private_constant'
private_constant :MY_VALUE_1
Upvotes: 1