Question

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"

Was it helpful?

Solution

like this:

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

OTHER TIPS

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

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.

In irb:

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

Or you could drop to irb

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top