0

I am trying to assign a variable within eval, and then print it out. The code is:

eval "foo=nil"
puts foo

What I get is:

undefined local variable or method `foo' for main:Object (NameError)

When I use puts within the eval, I get no errors. This means that foo is scoped within the eval. How can I get it to be outside the eval scope, yet not as a global variable?

sawa
  • 165,429
  • 45
  • 277
  • 381
user1134991
  • 3,003
  • 2
  • 25
  • 35
  • 3
    http://stackoverflow.com/questions/715010/ruby-eval-behaves-differently-in-irb-versus-in-a-file/715159#715159 http://stackoverflow.com/questions/14404198/ruby-1-9-3-define-var-with-eval – Ximik Jul 01 '14 at 08:25
  • 2
    You can't, see [How to dynamically create a local variable?](http://stackoverflow.com/questions/18552891/how-to-dynamically-create-a-local-variable) – Stefan Jul 01 '14 at 08:32
  • 1
    @Stefan I think you once had an answer to this question using a binding object. I cannot find the question immediately. – sawa Jul 01 '14 at 08:33
  • 1
    @sawa that was about creating local variables in IRB: http://stackoverflow.com/questions/17842765/how-do-i-dynamically-create-a-local-variable-in-ruby – Stefan Jul 01 '14 at 08:35
  • `foo` is not global variable. `$foo` is global variable. – Darek Nędza Jul 01 '14 at 10:47

1 Answers1

2

I think foo is going out of scope in your eval.

if you declare it before your eval it will work ok. Eg;

foo='foo'
eval "foo=nil"
puts foo.to_s

output:

=> nil
John C
  • 4,276
  • 2
  • 17
  • 28