Reputation: 789
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"
Upvotes: 8
Views: 2616
Reputation: 667
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
Upvotes: 0
Reputation: 12427
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
Upvotes: 4
Reputation: 1297
In irb:
eval(File.read('myarray.rb'),binding)
Or you could drop to irb
Upvotes: 1
Reputation: 369556
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.
Upvotes: 1