$>ruby -e ‘str = “a = 2”; eval(str); puts a’
-e:1: undefined local variable or method `a’ for #Object:0x124b00
(NameError)
I know I can do something like ‘bar = eval(str)’ to get the value to which
str evaluates to, but I was hoping it would remember the variable name,
mostly because the string I am evaluating has more than one operation in it,
and the assignment only captures the last. Is this not possible? Thanks.
Matt
p.s. If I do the equivalent in IRB, it remembers the variable name.
irb(main):005:0> str = "a =2; b =3"
"a =2; b =3"
irb(main):006:0> eval(str)
3
irb(main):007:0> a
2
irb(main):008:0> b
3
irb(main):009:0>
I can answer this part. Please see “ri eval” output for more details:
As of Ruby 1.8, local variables assigned within an eval are
only available after the eval if they were defined at the outter
scope before the eval executed. In this way eval has the same
scoping rules as blocks.
$>ruby -e ‘str = “a = 2”; eval(str); puts a’
-e:1: undefined local variable or method `a’ for #Object:0x124b00
(NameError)
p.s. If I do the equivalent in IRB, it remembers the variable name.
I don’t know how irb manages to do it : some “binding” magic I guess.
Can experts shed some light please?
I can answer this part. Please see “ri eval” output for more details:
As of Ruby 1.8, local variables assigned within an eval are
only available after the eval if they were defined at the outter
scope before the eval executed. In this way eval has the same
scoping rules as blocks.
$>ruby -e ‘str = “a = 2”; eval(str); puts a’
-e:1: undefined local variable or method `a’ for #Object:0x124b00
(NameError)
p.s. If I do the equivalent in IRB, it remembers the variable name.
I don’t know how irb manages to do it : some “binding” magic I guess.
Can experts shed some light please?
svg% ruby -ve ‘a=nil; str = “a=2”; eval(str,binding); puts a’
^^^^
Of course, by creating ‘a’ here, this has to work. I would like
to know how irb can make it work without pre-creation of “a”.
My example work not because the variable was
created before the eval, but because ruby has
seen at compile time that `a’ is a variable.
If you write
ruby -ve ‘str = “a=2”; eval(str,binding); puts a’
at compile time, puts a' is interpreted as a method call, i.e. puts a()’
To further illustrate this point:
irb(main):001:0> VERSION
=> “1.6.8”
irb(main):002:0> str = “a = 2”; eval(str); puts a
NameError: undefined local variable or method `a’ for #Object:0x810fcd8
from (irb):2
irb(main):003:0> a
=> 2
irb(main):004:0>