Assigning a instance variable using eval works fine whereas the other doesn't. Trying to understand whats happening here. Any help is appreciated.
>> var = "a value"
=> "a value"
>> @v
=> nil
>> eval "@v = var"
=> "a value"
>> @v
=> "a value"
>> eval "var_new = var"
=> "a value"
>> var_new
NameError: undefined local variable or method `var_new' for main:Object
from (irb):7
from C:/Ruby193/bin/irb:12:in `<main>'
eval simply has its own scope. You can access variables that were defined before but you will not get access to variables that are defined inside eval.
Scoping-wise, your example is similar to:
var = "a value"
1.times do # create new scope
new_var = var
end
new_var
# NameError: undefined local variable or method `new_var' for main:Object
eval creates its own scope:
>> i = 1; local_variables.count
=> 2
>> eval "j = 1; local_variables.count"
=> 3
>> local_variables.count
=> 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With