Unfortunately, Ruby does not support such passing mechanism as e.g. AWK:
> awk -v a=1 'BEGIN {print a}'
> 1
It means you cannot pass named values into your script directly.
Using cmd options may help:
> ruby script.rb val_0 val_1 val_2
# script.rb
puts ARGV[0] # => val_0
puts ARGV[1] # => val_1
puts ARGV[2] # => val_2
Ruby stores all cmd arguments in the ARGV
array, the scriptname itself can be captured using the $PROGRAM_NAME
variable.
The obvious disadvantage is that you depend on the order of values.
If you need only Boolean switches use the option -s
of the Ruby interpreter:
> ruby -s -e 'puts "So do I!" if $agreed' -- -agreed
> So do I!
Please note the --
switch, otherwise Ruby will complain about a nonexistent option -agreed
, so pass it as a switch to your cmd invokation. You don't need it in the following case:
> ruby -s script_with_switches.rb -agreed
> So do I!
The disadvantage is that you mess with global variables and have only logical true/false values.
You can access values from environment variables:
> FIRST_NAME='Andy Warhol' ruby -e 'puts ENV["FIRST_NAME"]'
> Andy Warhol
Drawbacks are present here to, you have to set all the variables before the script invocation (only for your ruby process) or to export them (shells like BASH):
> export FIRST_NAME='Andy Warhol'
> ruby -e 'puts ENV["FIRST_NAME"]'
In the latter case, your data will be readable for everybody in the same shell session and for all subprocesses, which can be a serious security implication.
And at least you can implement an option parser using getoptlong and optparse.
Happy hacking!