8

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"

iljkj
  • 779
  • 1
  • 9
  • 13

4 Answers4

9

like this:

def my_array
    [1, 2, 3, 4, 5]
end
horseyguy
  • 29,455
  • 20
  • 103
  • 145
  • Note, if you are doing something more complicated than creating an array, you may want to setup a local instance variable to hold the resulting object... such as my "load" initializes a connection to an API for testing, with the credentials and everything., so after my "load" I just do api = my_api – TommyTheKid Feb 13 '15 at 21:43
2

You can also require your script and access that data in a few other ways. A local variable cannot be accessed, but these other three data types can be accessed within the scope, similar to the method definition.

MY_ARRAY = [1, 2, 3, 4 5] #constant
@my_array = [1, 2, 3, 4 5] #instance variable
@@my_array = [1, 2, 3, 4 5] #class variable
def my_array # method definition
  [1, 2, 3, 4 5]
end
sealocal
  • 10,897
  • 3
  • 37
  • 50
1

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
  • 363,080
  • 75
  • 446
  • 653
1

In irb:

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

Or you could drop to irb

highBandWidth
  • 16,751
  • 20
  • 84
  • 131
raggi
  • 1,290
  • 9
  • 12
  • i was really hoping this would work but i still get "undefined local variable" error – iljkj Sep 26 '10 at 07:07
  • can you show the exact code you tested with, or maybe a dump of the session, because this does work. – raggi Sep 26 '10 at 11:38
  • 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 Sep 26 '10 at 15:39
  • oh, sorry, you need to pass a binding to eval: eval(File.read('myarray.rb'), binding) – raggi Oct 20 '10 at 13:44