Ruby local variable is undefined

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 : v1 = 1 class MyClass # SCOPE GATE: entering class v2 = 2 local_variables # => [“v2”] def my_method # SCOPE GATE: entering … Read more

Dynamically set local variables in Ruby [duplicate]

As an additional information for future readers, starting from ruby 2.1.0 you can using binding.local_variable_get and binding.local_variable_set: def foo a = 1 b = binding b.local_variable_set(:a, 2) # set existing local variable `a’ b.local_variable_set(:c, 3) # create new local variable `c’ # `c’ exists only in binding. b.local_variable_get(:a) #=> 2 b.local_variable_get(:c) #=> 3 p a … Read more

UnboundLocalError trying to use a variable (supposed to be global) that is (re)assigned (even after first use)

Python treats variables in functions differently depending on whether you assign values to them from inside or outside the function. If a variable is assigned within a function, it is treated by default as a local variable. Therefore, when you uncomment the line, you are trying to reference the local variable c before any value … Read more

Why a variable defined global is undefined? [duplicate]

You have just stumbled on a js “feature” called hoisting var myname = “global”; // global variable function func() { alert(myname); // “undefined” var myname = “local”; alert(myname); // “local” } func(); In this code when you define func the compiler looks at the function body. It sees that you are declaring a variable called … Read more

How to get local variables updated, when using the `exec` call?

This issue is somewhat discussed in the Python3 bug list. Ultimately, to get this behavior, you need to do: def foo(): ldict = {} exec(“a=3”,globals(),ldict) a = ldict[‘a’] print(a) And if you check the Python3 documentation on exec, you’ll see the following note: The default locals act as described for function locals() below: modifications to … Read more