accessing variables in loaded source while in irb
Asked Answered
B

5

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"

Braziel answered 25/9, 2010 at 12:19 Comment(1)
T
9

like this:

def my_array
    [1, 2, 3, 4, 5]
end
Tuinal answered 25/9, 2010 at 12:51 Comment(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_apiDinesen
P
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
Paresh answered 8/11, 2015 at 19:36 Comment(0)
W
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.

Wellborn answered 25/9, 2010 at 13:42 Comment(0)
W
1

In irb:

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

Or you could drop to irb

Written answered 26/9, 2010 at 2:44 Comment(4)
i was really hoping this would work but i still get "undefined local variable" errorBraziel
can you show the exact code you tested with, or maybe a dump of the session, because this does work.Written
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.Braziel
oh, sorry, you need to pass a binding to eval: eval(File.read('myarray.rb'), binding)Written
R
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

Ronnyronsard answered 14/10, 2023 at 22:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.