Ruby Command Line Options

In this article, we’re going to explore the following topics:

  • silence, medium & verbose levels
  • add a loop around a script
  • Rails and the RUBYOPT environment variable

Disclaimer

Ruby provides a bunch of very interesting options.

The goal of this article is not to describe each available option but to cherry-pick and dig into the most interesting ones.

As the man ruby doesn’t dig into each option this article will go beyond and provide a bunch of examples to illustrate the concept behind each described option.

Silence, medium & verbose levels

The -W[level] option allows Ruby to calibrate the verbosity level of the running program.

The available levels are:

  • -W0: the silence level

produces

nil
printed

This option sets the $VERBOSE global variable to nil.

It also silences all of the Ruby built-in warning and any call to the warn method.

  • -W1: the medium level

produces

false
printed
warning: key :my_key is duplicated and overwritten on line 3

This option sets the $VERBOSE global variable to false.

It prints the interpreter level 1 warnings — as the “duplicated hash keys” warning — and doesn’t silence the warn method.

  • -W2: the verbose level

produces

true
printed
warning: method redefined; discarding old my_method

This option sets the $VERBOSE global variable to true.

It prints the interpreter level 2 warnings — as the “method redefinition” warning — and doesn’t silence the warn method.

Add a loop around your script

The -n option causes Ruby to assume the following loop around your script

while gets
...
end

The content of each line is available in the $_ magic variable.

So, for the following consumer.rb script

puts "line: #{$_}"

and the following input.txt file

I love Ruby
More than C#

the output is

$> ruby -n consumer.rb input.txt
line: I love Ruby
line: More than C#

By using the -n option, the final version of the consumer.rb script is

I invite you to read the ruby man page for further information.

Rails and the RUBYOPT environment variable

Ruby on Rails is probably the most used Ruby project in the world.

When you call the rails console command then the

ruby bin/rails console is executed behind the scene.

Otherwise, it’s possible to interact with the Ruby options by using the RUBYOPT environment variable

$> RUBYOPT="-W0" bin/rails console

Here, the rails command will be executed with a silence verbosity level.

Voilà !


Thank you for taking the time to read this post :-)

Feel free to 👏 and share this article if it has been useful for you. 🚀

Here is a link to my last article: Context Binding in Ruby.

Like what you read? Give Mehdi Farsi a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.