anemaria20
anemaria20

Reputation: 1728

Why can I access constants inside an array in Ruby?

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

Answers (3)

tokland
tokland

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

Wayne Conrad
Wayne Conrad

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:

  • Defining a class using class SomeName
  • Defining a module using module SomeName
  • Defining a function using def some_name

Upvotes: 4

Axe
Axe

Reputation: 692

If you want to prevent visibility outside the class (hiding) you can use 'private_constant'

private_constant :MY_VALUE_1

Upvotes: 1

Related Questions