Photo by Mark Olsen on Unsplash

Ruby Command Line Options

Tech - RubyCademy
RubyCademy
Published in
2 min readAug 9, 2018

--

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 warnings 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 warning — 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 scenes.

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.

Ruby Mastery

We’re currently finalizing our first online course: Ruby Mastery.

Join the list for an exclusive release alert! 🔔

🔗 Ruby Mastery by RubyCademy

Also, you can follow us on x.com as we’re very active on this platform. Indeed, we post elaborate code examples every day.

💚

--

--