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

Before to start

I’m thrilled to share with you our latest project: Fun Facts about Ruby — Volume 1

Please feel free to spread the word and share this post! 🙏

Thank you for your time!

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à !

May I have your attention please 🎤🎤

Feel free to subscribe here: www.rubycademy.com