Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable assignment using eval

Tags:

variables

ruby

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>'
like image 434
Bala Avatar asked Mar 25 '26 10:03

Bala


2 Answers

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
like image 56
Patrick Oscity Avatar answered Mar 28 '26 00:03

Patrick Oscity


eval creates its own scope:

>> i = 1; local_variables.count
=> 2
>> eval "j = 1; local_variables.count"
=> 3
>> local_variables.count
=> 2
like image 31
Denis de Bernardy Avatar answered Mar 27 '26 23:03

Denis de Bernardy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!