tags:

views:

30

answers:

3

Say I have a file named test1.rb with the following code:

my_array = [1, 2, 3, 4 5]

Then I run irb and get an irb prompt and run "require 'test1'. At this point I am expecting to be able to access my_array. But if I try to do something like...

puts my_array

irb tells me "my_array" is undefined. Is there a way to access "my_array"

A: 

like this:

def my_array
    [1, 2, 3, 4, 5]
end
banister
This accomplishes what I want. thank you
iljkj
A: 

No, there isn't. Local variables are always local to the scope they are defined in. That's why they are called local variables, after all.

Jörg W Mittag
A: 

In irb:

  eval(File.read('myarray.rb'))

Or you could drop to irb

raggi
i was really hoping this would work but i still get "undefined local variable" error
iljkj
can you show the exact code you tested with, or maybe a dump of the session, because this does work.
raggi
in a file called "myarray.rb" i have "my_array = (1..5).to_a". then in irb i do eval(File.read('myarray.rb')) which outputs "[1, 2, 3, 4, 5]". That is good but i want to then be able to access "my_array" but it doesn't exist in the current session of irb.
iljkj
oh, sorry, you need to pass a binding to eval: eval(File.read('myarray.rb'), binding)
raggi