I have the following Ruby code:
local_var = "Hello"
def hello
puts local_var
end
hello
I get the following error:
local_variables.rb:4:in 'hello': undefined local variable or method 'local_var'
for main:Object (NameError) from local_variables.rb:7:in '<main>'
I always thought that local variables are not accessible from outside of the block, function, closure, etc.
But now I defined local variable in the file and try to get an access from the function INSIDE the same file.
What’s wrong with my understanding?
In Ruby local variables only accessible in the scope that they are defined. Whenever you enter/leave a Class, a Module or a Method definiton your scope changes in Ruby.
For instance :
These entering and leaving points are called Scope Gates. Since you enter through Scope Gate via method definition you cannot access your
local_varinsidehellomethod.You can use Scope Flattening concept the pass your variable through these gates.
For instance instead of using
deffor defining your method you can useModule#define_method.In the same way you can define your classes via
Class#Newso that your scope does not change when you pass through class definition.instead of
In the same way you should use
Module#Newif you want to pass your local variables through Module gates.Example is taken from Metaprogramming Ruby