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 this:
def my_array
[1, 2, 3, 4, 5]
end
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With