7

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
  • 769
  • 1
  • 8
  • 13

4 Answers4

8

like this:

def my_array
    [1, 2, 3, 4, 5]
end
horseyguy
  • 28,690
  • 18
  • 100
  • 139
  • 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
  • 8,788
  • 1
  • 34
  • 48
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
  • 351,196
  • 74
  • 424
  • 630
1

In irb:

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

Or you could drop to irb

highBandWidth
  • 15,945
  • 18
  • 80
  • 129
raggi
  • 1,270
  • 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