Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

Running another ruby script from a ruby script

In ruby, is it possible to specify to call another ruby script using the same ruby interpreter as the original script is being run by?

For example, if a.rb runs b.rb a couple of times, is it possible to replace

system("ruby", "b.rb", "foo", "bar")

with something like

run_ruby("b.rb", "foo", "bar")

so that if you used ruby1.9.1 a.rb on the original, ruby1.9.1 would be used on b.rb, but if you just used ruby a.rb on the original, ruby would be used on b.rb?

I'd prefer not to use shebangs, as I'd like it to be able to run on different computers, some of which don't have /usr/bin/env.

Edit: I didn't mean load or require and the like, but spawning new processes (so I can use multiple CPUs).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
require "b.rb"

will execute the contents of b.rb (you call leave off the ".rb", and there is a search path). In your case, you would probably do something like:

a.rb:

require "b.rb";
b("Hello", "world")

b.rb:

def b(first, second)
  puts first + ", " + second
end

Note that if you use require, Ruby will only load and execute the file once (every time you call load it will be reloaded), but you can call methods defined in the file as many times as you want.

As things get more complex, you will want to move towards an object-oriented design.

EDIT: In that case, you should look into Ruby threading. A simple example is:

a.rb:

require "b";
t1 = Thread.new{b("Hello", "world");}
t2 = Thread.new{b("Hello", "galaxy");}
t1.join
t2.join

b.rb:

def b(first, second)
  10.times {
    puts first + ", " + second;
    sleep(0.1);
  }
end

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...