3

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>'
2
  • eval creates a new scope and var_new is local to that scope. Commented Jun 18, 2013 at 15:00
  • whereas @v is an instance variable of the containing object (inside irb that's an instance of Object - at least it is in 1.8.7), so it can be accessed from eval, and remains afterwards due to being scoped to the object. Commented Jun 18, 2013 at 15:03

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

Comments

3

eval creates its own scope:

>> i = 1; local_variables.count
=> 2
>> eval "j = 1; local_variables.count"
=> 3
>> local_variables.count
=> 2

2 Comments

does that mean instance variables are not in eval's own scope (local scope)?
instance variables are still around, and they're still in the context of the object. See the above tests, by replacing i and j by @i and @j, and local_variables with instance_variables. You'll end up incrementing the number of instance_variables as expected.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.