Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accessing variables in loaded source while in irb

Tags:

ruby

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"

like image 1000
iljkj Avatar asked Sep 25 '10 12:09

iljkj


2 Answers

like this:

def my_array
    [1, 2, 3, 4, 5]
end
like image 197
horseyguy Avatar answered Sep 27 '22 21:09

horseyguy


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
like image 30
sealocal Avatar answered Sep 27 '22 23:09

sealocal