iljkj
iljkj

Reputation: 789

accessing variables in loaded source while in irb

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

Answers (5)

m3.b
m3.b

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

sealocal
sealocal

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

raggi
raggi

Reputation: 1297

In irb:

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

Or you could drop to irb

Upvotes: 1

Jörg W Mittag
Jörg W Mittag

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

horseyguy
horseyguy

Reputation: 29915

like this:

def my_array
    [1, 2, 3, 4, 5]
end

Upvotes: 9

Related Questions