Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass variables between ruby scripts?

Tags:

ruby

I am mostly interested in the theory of this than an actual code solution. How can I have one main ruby script invoking other scripts and sharing variables between each other? I am a bit confused.. Do I need to use environmental vars, session vars, methods, models, controllers, what is the best way to do it!!?

like image 986
Xwris Stoixeia Avatar asked Dec 20 '22 22:12

Xwris Stoixeia


2 Answers

Let's assume you have a script.rb, which contains this:

$var = :value
def get; A end
load 'another_script.rb'
get  # Will it succeed?

When you run ruby script.rb, you spawn a Ruby process which will read the contents of script.rb and execute every line. The Ruby interpreter has an execution state which holds information such as object data, the variables that reference them, which scope they belong to, which method you're currently in and so much more.

When the interpreter reads the $var = :value line, it modifies its own state. It stores a global variable which references the newly-created symbol object. Next, it defines a method which will return the value referenced by the A constant. Calling it at this point will raise a NameError, since the constant does not exist. When it reaches the load 'another_script.rb' line, it is analogous to running ruby another_script.rb, except no second process is started. The contents of the script are read and interpreted within the same execution context.

Suppose another_script.rb contains the following:

$var = :changed
class A; end

The $var variable, which previously referenced the :value symbol, will now reference the :changed symbol. Then, a Class object will be created and assigned to the new A constant.

After loading this script, the call to get will succeed. Another implication is that order matters. For example:

load 'another_script.rb'
$var = :value

Whatever another_script.rb set $var to will be lost since it will be overridden immediately after it has finished executing.

No matter how many scripts you load, require or eval, as long as they are running on the same process, they will always share the same data. Only local variables will not be shared between files. Things get complicated when you want to share data between two different Ruby interpreters:

ruby script.rb &
ruby another_script.rb &

In that case, you have to use inter-process communication.

like image 152
Matheus Moreira Avatar answered Jan 05 '23 10:01

Matheus Moreira


If you want two Ruby processes to communicate (even if they are running on different machines), then Druby is the built in way.

like image 32
steenslag Avatar answered Jan 05 '23 10:01

steenslag