Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I access constants inside an array in Ruby?

Tags:

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 []?

like image 905
anemaria20 Avatar asked Sep 07 '25 10:09

anemaria20


1 Answers

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
like image 54
Wayne Conrad Avatar answered Sep 09 '25 09:09

Wayne Conrad