Useful ruby command line options

-e and -r flag

If you’re working with Ruby scripting, you may encounter situations where you need to run Ruby code that’s saved in a file.
In such scenarios, you can use the ruby filename.rb command to execute the code directly from the command line.
This command is quite useful because it allows you to easily test and debug your Ruby scripts without having to open them in an editor or an IDE.

When you want to quickly validate Ruby methods or calculations, or simply run Ruby code directly in the terminal without creating a script file, you can use the Ruby -e flag.

The -e flag is a command-line option in Ruby that allows you to execute code directly from the command line without creating a separate Ruby script file.
This means that you can run Ruby code without the need for a script file.
Below are some common usages and more details on how to use the -e flag.

  1. execute ruby code
ruby -e 'puts "Hello, world!"'

=> Hello, world!

# you can put multiple statements also using ;

ruby -e 'puts "Hi"; puts "Let us code"'

=> Hi
   Let us code
  1. quick evalution of the expressions
ruby -e "puts 2 + 2"

=> 4

# with string interpolation
ruby -e 'puts "Today is #{Time.now}"'

=> Today is 2021-10-04 21:39:50 +0530
  1. you can even access ARGV using the -e flag
ruby -e 'puts "Hello " +ARGV[0]+"!"' "Rakesh"

=> Hello Rakesh!
  1. with combination of -r you could require the external lib and use it with -e command
ruby -rjson -e 'puts JSON.parse("{\"firstname\":\"rakesh\", \"lastname\":\"verma\"}")'

=> {"firstname"=>"rakesh", "lastname"=>"verma"}

Please note that the -e option in Ruby allows you to run a one-line command directly from the terminal, without having to create a separate Ruby file.
This can be useful for quick, one-off tasks or for scripting purposes.
However, for more substantial scripts or programs, it is generally better to create a separate Ruby file.

-c flag

An additional flag that can be useful is -c.
This flag performs a syntax check on a Ruby file without executing it.
It can be helpful when resolving git merge conflicts, as it allows you to double check that there are no stray lines in your Ruby code.
-c Causes Ruby to check the syntax of the script and exit without executing.
If there are no syntax errors, Ruby will print “Syntax OK” to the standard output.

get all supported ruby command flags

To see all options, run man ruby from the command line.
ex:

     The Ruby interpreter accepts the following command-line options (switches).  They are quite similar to those of perl(1).

     --copyright    Prints the copyright notice, and quits immediately without running any script.

     --version      Prints the version of the Ruby interpreter, and quits immediately without running any script.

     -0[octal]      (The digit “zero”.) Specifies the input record separator ($/) as an octal number. If no digit is given, the null character is taken as the separator.
                    Other switches may follow the digits.  -00 turns Ruby into paragraph mode.  -0777 makes Ruby read whole file at once as a single string since there
                    is no legal character with that value.

     -C directory
     -X directory   Causes Ruby to switch to the directory.

     -E external[:internal]
     --encoding external[:internal]
                    Specifies the default value(s) for external encodings and internal encoding. Values should be separated with colon (:).

                    You can omit the one for internal encodings, then the value (Encoding.default_internal) will be nil.

     --external-encoding=encoding
     --internal-encoding=encoding
                    Specify the default external or internal character encoding

     -F pattern     Specifies input field separator ($;).

     -I directory   Used to tell Ruby where to load the library scripts.  Directory path will be added to the load-path variable ($:).

     -K kcode       Specifies KANJI (Japanese) encoding. The default value for script encodings (__ENCODING__) and external encodings (Encoding.default_external) will be
                    the specified one. kcode can be one of

                          e       EUC-JP

                          s       Windows-31J (CP932)

                          u       UTF-8

                          n       ASCII-8BIT (BINARY)

     -S             Makes Ruby use the PATH environment variable to search for script, unless its name begins with a slash.  This is used to emulate #! on machines that
                    don't support it, in the following manner:

                          #! /usr/local/bin/ruby
                         # This line makes the next one a comment in Ruby \
                            exec /usr/local/bin/ruby -S $0 $*

                    On some systems $0 does not always contain the full pathname, so you need the -S switch to tell Ruby to search for the script if necessary (to handle
                    embedded spaces and such).  A better construct than $* would be ${1+"$@"}, but it does not work if the script is being interpreted by csh(1)
     -T[level=1]    Turns on taint checks at the specified level (default 1).

     -U             Sets the default value for internal encodings (Encoding.default_internal) to UTF-8.

     -W[level=2]    Turns on verbose mode at the specified level without printing the version message at the beginning. The level can be;

                          0       Verbose mode is "silence". It sets the $VERBOSE to nil.

                          1       Verbose mode is "medium". It sets the $VERBOSE to false.

                          2 (default) Verbose mode is "verbose". It sets the $VERBOSE to true.  -W2 is the same as -w

     -a             Turns on auto-split mode when used with -n or -p.  In auto-split mode, Ruby executes
                          $F = $_.split
                    at beginning of each loop.

     --backtrace-limit=num
                    Limits the maximum length of backtraces to num lines (default -1, meaning no limit).

     -c             Causes Ruby to check the syntax of the script and exit without executing. If there are no syntax errors, Ruby will print “Syntax OK” to the standard
                    output.

     -d
     --debug        Turns on debug mode.  $DEBUG will be set to true.

     -e command     Specifies script from command-line while telling Ruby not to search the rest of the arguments for a script file name.

     -h
     --help         Prints a summary of the options.

     -i extension   Specifies in-place-edit mode.  The extension, if specified, is added to old file name to make a backup copy.  For example:

                          % echo matz > /tmp/junk
                          % cat /tmp/junk
                          matz
                          % ruby -p -i.bak -e '$_.upcase!' /tmp/junk
                          % cat /tmp/junk
                          MATZ
                          % cat /tmp/junk.bak
                          matz

     -l             (The lowercase letter “ell”.) Enables automatic line-ending processing, which means to firstly set $\ to the value of $/, and secondly chops every line read using chomp!.

     -n             Causes Ruby to assume the following loop around your script, which makes it iterate over file name arguments somewhat like sed -n or awk.

                          while gets
                            ...
                          end

     -p             Acts mostly same as -n switch, but print the value of variable $_ at the each end of the loop.  For example:

                          % echo matz | ruby -p -e '$_.tr! "a-z", "A-Z"'
                          MATZ

     -r library     Causes Ruby to load the library using require.  It is useful when using -n or -p.

     -s             Enables some switch parsing for switches after script name but before any file name arguments (or before a --).  Any switches found there are removed
                    from ARGV and set the corresponding variable in the script.  For example:

                          #! /usr/local/bin/ruby -s
                          # prints "true" if invoked with `-xyz' switch.
                          print "true\n" if $xyz

     -v             Enables verbose mode.  Ruby will print its version at the beginning and set the variable $VERBOSE to true.  Some methods print extra messages if this
                    variable is true.  If this switch is given, and no other switches are present, Ruby quits after printing its version.

     -w             Enables verbose mode without printing version message at the beginning.  It sets the $VERBOSE variable to true.

     -x[directory]  Tells Ruby that the script is embedded in a message.  Leading garbage will be discarded until the first line that starts with “#!” and contains the
                    string, “ruby”.  Any meaningful switches on that line will be applied.  The end of the script must be specified with either EOF, ^D (control-D), ^Z
                    (control-Z), or the reserved word __END__.  If the directory name is specified, Ruby will switch to that directory before executing script.

     -y
     --yydebug      This option is not guaranteed to be compatible.

                    Turns on compiler debug mode.  Ruby will print a bunch of internal state messages during compilation.  Only specify this switch you are going to
                    debug the Ruby interpreter.

     --disable-FEATURE
     --enable-FEATURE
                    Disables (or enables) the specified FEATURE.
                    --disable-gems
                    --enable-gems      Disables (or enables) RubyGems libraries.  By default, Ruby will load the latest version of each installed gem. The Gem constant
                                       is true if RubyGems is enabled, false if otherwise.

                    --disable-rubyopt
                    --enable-rubyopt   Ignores (or considers) the RUBYOPT environment variable. By default, Ruby considers the variable.

                    --disable-all
                    --enable-all       Disables (or enables) all features.

     --dump=target  Dump some information.

                    Prints the specified target.  target can be one of:

                          version Print version description (same as --version).

                          usage   Print a brief usage message (same as -h).

                          help    Show long help message (same as --help).

                          syntax  Check syntax (same as -c --yydebug).

                    Or one of the following, which are intended for debugging the interpreter:

                          yydebug                 Enable compiler debug mode (same as --yydebug).

                          parsetree               Print a textual representation of the Ruby AST for the program.

                          parsetree_with_comment  Print a textual representation of the Ruby AST for the program, but with each node annoted with the associated Ruby
                                                  source code.

                          insns                   Print a list of disassembled bytecode instructions.

                          insns_without_opt       Print the list of disassembled bytecode instructions before various optimizations have been applied.

     --verbose      Enables verbose mode without printing version message at the beginning.  It sets the $VERBOSE variable to true.  If this switch is given, and no
                    script arguments (script file or -e options) are present, Ruby quits immediately.

     --crash-report=template
                    Sets the template of path name to save crash report.  See RUBY_CRASH_REPORT environment variable for details.