I would now like to pass arguments to the two scripts (for simplicity
the same arguments in each case), andI would like to be able to do this
via the third script eg
Ruby takes its arguments from a global array called ARGV. That array
is special because it is initialized by the interpreter, buy from then
on it is a regular mutable array.
In particular you can modify it:
def with_argv(*argv)
original_argv = ARGV.dup
ARGV.replace(argv)
yield
ARGV.replace(original_argv)
end
You would use that method this way:
with_argv(1, 2, 3) do
require ‘/opt/ruby/script1’
end
Not that it is a good practice, you normall would invoke the scripts
using #system or whatever, but since you say you are not a programmer
that would fit into your current model if you don’t feel confident to
explore system.
Another fine point is that in general a script will expect strings in
ARGV, so perhaps a conversion would be handy to free the caller from
this nuance.
This is not exception safe. You’d rather want the restoration in an
ensure block. I would also return the result of yield rather than the
result of doing ARGV.replace.
You would use that method this way:
with_argv(1, 2, 3) do
require ‘/opt/ruby/script1’
end
Not that it is a good practice, you normall would invoke the scripts
using #system or whatever, but since you say you are not a programmer
that would fit into your current model if you don’t feel confident to
explore system.
“Require” is not a good tool in this case as it will load a script
only once and is primarily intended to be used for loading library
code. If at all I would rather use “load”. So this would be an
alternative
def with_args(*args)
backup = ARGV.dup
begin
ARGV.replace(args)
yield
ensure
ARGV.replace(backup)
end
end
Robert, Xavier, many thanks - not only is my problem solved but (perhaps
more importantly) my knowledge and appreciation of Ruby have grown. For
the benfit of others, here is what I now have:-
def with_argv(*args)
backup = ARGV.dup
begin
ARGV.replace(args)
yield
ensure
ARGV.replace(backup)
end
end
with_argv(*ARGV) do
require ‘/opt/ruby/script1.rb’
require ‘/opt/ruby/script2.rb’
end
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.