Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Let's assume you have a <code>script.rb</code>, which contains this:</p> <pre><code>$var = :value def get; A end load 'another_script.rb' get # Will it succeed? </code></pre> <p>When you run <code>ruby script.rb</code>, you spawn a Ruby process which will read the contents of <code>script.rb</code> and execute every line. The Ruby interpreter has an <em>execution state</em> 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.</p> <p>When the interpreter reads the <code>$var = :value</code> 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 <code>A</code> constant. Calling it at this point will raise a <code>NameError</code>, since the constant does not exist. When it reaches the <code>load 'another_script.rb'</code> line, it is analogous to running <code>ruby another_script.rb</code>, except no second process is started. The contents of the script are read and interpreted <em>within the same execution context</em>.</p> <p>Suppose <code>another_script.rb</code> contains the following:</p> <pre><code>$var = :changed class A; end </code></pre> <p>The <code>$var</code> variable, which previously referenced the <code>:value</code> symbol, will now reference the <code>:changed</code> symbol. Then, a <code>Class</code> object will be created and assigned to the new <code>A</code> constant.</p> <p><em>After</em> loading this script, the call to <code>get</code> will succeed. Another implication is that <em>order matters</em>. For example:</p> <pre><code>load 'another_script.rb' $var = :value </code></pre> <p>Whatever <code>another_script.rb</code> set <code>$var</code> to will be lost since it will be overridden immediately after it has finished executing.</p> <p>No matter how many scripts you <code>load</code>, <code>require</code> or <code>eval</code>, as long as they are running on the same process, they will <em>always</em> share the same data. <a href="http://www.ruby-doc.org/core-1.9.3/Kernel.html#method-i-load" rel="nofollow">Only local variables will not be shared between files</a>. Things get complicated when you want to share data between two <em>different</em> Ruby interpreters:</p> <pre><code>ruby script.rb &amp; ruby another_script.rb &amp; </code></pre> <p>In that case, you have to use <a href="http://en.wikipedia.org/wiki/Inter-process_communication" rel="nofollow">inter-process communication</a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload