How to call an array from one ruby script to another

Can we call an array from one ruby script to another and access array
elements.?

for example : my first rb file

1.rb
$joe = “one”
$po = “two”
$so = “three”
names = [ $joe, $po, $so ]
second rb file

2.rb
require “1”
$trial = names[1]
puts $trial
But this didnt worked. Any help plz.

On Sun, Nov 27, 2011 at 1:17 PM, hari mahesh [email protected]
wrote:

second rb file

Variables that begin with dollar signs are global. So if you namei t
$names, then it will be available everywhere.

You could also define a function that returns the array. Toplevel
functions
are defined privately on Object, which nearly all objects inherit from,
making it essentially globally visible:

def names
[‘one’, ‘two’, ‘three’]
end

Depending on what you’re trying to do, there are a number of possible
ways
to handle this.

hi Hari,

Josh C. wrote in post #1033979:

Variables that begin with dollar signs are global. So if you namei t
$names, then it will be available everywhere.

this is true, but global variables are generally a bad idea - they can
gum up the works in unexpected ways… probably best to avoid them if
you can.

Depending on what you’re trying to do, there are a number of possible
ways
to handle this.

this is also true… if you give more background on what you want to
do, it would make it easier to offer helpful solutions.

a couple of things you could think about are a creating a Class in the
first script that defines the array to be used in the second (as Josh
mentions,) or using YAML to store and retrieve the array.

using a Class to define the array could look something like this:

1.rb

class GroupsOfStuff

attr_accessor :people, :cats

def initialize
  @people = ["Joe", "Po", "So"]
  @cats = ["Bill", "BooBoo", "Felix"]
end

end

2.rb

require ‘1’

groups = GroupsOfStuff.new

p groups.people
p groups.cats

returns:

=>[“Joe”, “Po”, “So”]
[“Bill”, “BooBoo”, “Felix”]

using YAML could look like this:

1.rb

require ‘yaml’

people = [“Joe”, “Po”, “So”]
cats = [“Bill”, “BooBoo”, “Felix”]

File.open(“groups_of_stuff.yml”, “w”) do |file|
file.puts people.to_yaml
file.puts cats.to_yaml
end

2.rb

require ‘1’

data = File.open(“groups_of_stuff.yml”)

YAML.each_document(data) do |doc|
p doc
end

data.close

returns:

=>[“Joe”, “Po”, “So”]
[“Bill”, “BooBoo”, “Felix”]

hth -

j