Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running another ruby script from a ruby script

Tags:

ruby

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).

like image 752
Andrew Grimm Avatar asked Apr 14 '10 05:04

Andrew Grimm


People also ask

How do I call a ruby script?

Press Ctrl twice to invoke the Run Anything popup. Type the ruby script. rb command and press Enter .

How do I run a .rb file in command prompt?

Open a command line window and navigate to your Ruby scripts directory using the cd command. Once there, you can list files, using the dir command on Windows or the ls command on Linux or OS X. Your Ruby files will all have the . rb file extension.

How do I make a ruby script executable?

You can make the script executable with the following command: chmod +x hello. rb . chmod is a shell command that allows us to change the permissions for a file. The +x specifies that the script should be executable.

How do I run a ruby script in Jenkins?

In the job configuration screen, scroll down to Build. Click on Add build step and choose Execute Batch Command. Depending on the environment that Jenkins operates on (Windows or UNIX), choose either Execute Windows Batch Command or Execute Shell. Scroll all the way down and click Save or Apply.


1 Answers

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 
like image 138
Matthew Flaschen Avatar answered Sep 28 '22 01:09

Matthew Flaschen