'Why do i keep getting undefined local variable or method "" for #<Context:0xf4b640> when i try to access the variable?

Even in this simple program, i just keep getting the same thing:

var = "string"

def ex()
  puts var
end

ex()

And it gives me: undefined local variable or method `var' for #Context:0xf4b640.

What is happening here???



Solution 1:[1]

External local variables are not accessible within methods defined with def keyword (as def creates brand new context, completely separated from its surrounding context). You can access it however in methods defined with define_method:

var = "string"

define_method :ex do
  puts var
end

ex

Note however, that you should rarely need this (and it can turn your coding life into hell). Just use objects and instance_variables instead.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 BroiSatse