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"

1

5 Answers 5

9

like this:

def my_array
    [1, 2, 3, 4, 5]
end
1
  • 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 Feb 13, 2015 at 21:43
4

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
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.

1

In irb:

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

Or you could drop to irb

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

Defining in your file

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

then calling it in your IRB, after loading and requiring

@my_array

Will work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.