Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include files in a command line with Ruby

When running ruby scripts as such

ruby some-script.rb

How would I include a file (e.g. configuration file) in it dynamically?

like image 616
Macha Avatar asked Mar 27 '09 13:03

Macha


People also ask

How do you pass command line arguments in Ruby?

How to Use Command-Line Arguments. In your Ruby programs, you can access any command-line arguments passed by the shell with the ARGV special variable. ARGV is an Array variable which holds, as strings, each argument passed by the shell.

How do I load files into IRB?

From the main menu, choose Tools | Load file/selection into IRB/Rails console.

How do you use commands in Ruby?

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.


2 Answers

As you have found, the -r option is your friend. It also works with IRB:

irb -ropen-uri

Will do the same as require 'open-uri'

FWIW, the most common thing I need to include via the command line is rubygems. And since newer versions of ruby come with gems built in I don't want to edit the file, but include it for testing. Luckily the folks who created gems added a little alias sugar.

You can do the following:

ruby -rubygems myscript.rb

Instead of the ugly:

ruby -rrubygems myscript.rb

OK, so it is one character, but thought it was extra polish to make me happier.

like image 73
csexton Avatar answered Oct 12 '22 15:10

csexton


Actually, I found it. It's the -r command line entry.

like image 34
Macha Avatar answered Oct 12 '22 15:10

Macha