Home > Software engineering >  Why do i keep getting undefined local variable or method "" for #<Context:0xf4b640>
Why do i keep getting undefined local variable or method "" for #<Context:0xf4b640>

Time:04-21

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

CodePudding user response:

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.

  •  Tags:  
  • ruby
  • Related