Reputation: 815
For reasons that are a little hard to explain, I need to do the following: I have a master.rb
file that sets some global like: a = 1
. I want to call another file other_file.rb
that will run with the globals that were set in the master file. In python I'd use runpy.run_module( 'other_module', globals() )
.
Can anyone think of an equivalent in Ruby? I've looked at require
, include
, and load
, but none seem to do quite what I need, specifically they don't pull the globals into the other_file.rb
. Note that I am not trying to fork a new process, just hand execution over to "other_module" while maintaining the state of the globals.
Upvotes: 3
Views: 82
Reputation: 211560
If you absolutely must, you can use globals, and they're declared with the $
prefix. They are highly discouraged because there is only one global namespace, which makes collisions possible. Generally they are used for interpreter configuration, like $LOAD_PATH
.
A better approach is to use a module that has instance variables:
module MyContainer
def self.settings
@settings ||= { }
end
end
MyContainer.settings[:foo] = :bar
This has the advantage of keeping your variables contained in a namespace while not preventing other sub-programs from accessing them.
Keep in mind this will only work within the context of the same Ruby process or children created using fork
, so using system
or exec
will not work. Remember also that forked processes need to use IPC to communicate with their parent.
Upvotes: 4
Reputation: 10662
a=1
is not a global variable, it is a local variable that gets scoped to the file. If you really nee this behavior, use $a=1
to set global variables.
Upvotes: 4