Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading