Reputation: 11234
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>'
Upvotes: 3
Views: 1322
Reputation: 78423
eval creates its own scope:
>> i = 1; local_variables.count
=> 2
>> eval "j = 1; local_variables.count"
=> 3
>> local_variables.count
=> 2
Upvotes: 3
Reputation: 118261
Do kind of introspection as below :
var = "a value"
eval "var_new = var,defined?(var_new)" #=> ["a value", "local-variable"]
defined?(var_new) #=>nil
defined?(var) #=>"local-variable"
defined?(temp) #=>nil
You can see var_new is known to only inside the eval
. Outside of eval
temp and var_new both are same.
Upvotes: 2
Reputation: 54674
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
Upvotes: 3