Kashyap
Kashyap

Reputation: 17441

How to pass parameters to ruby command line script

I pass script to ruby via STDIN. E.g.,

$ ruby << EE
> puts "args: #{ARGV}"
> EE
args: []
$ ruby << EE
> puts "args: #{ARGV}"
> EE 'arg1' 'arg2'
> EE
-:2: syntax error, unexpected tSTRING_BEG, expecting keyword_do or '{' or '('
EE 'arg1' 'arg2'
    ^
$ ruby 'arg1' 'arg2' << EE
> puts "args: #{ARGV}"
> EE
ruby: No such file or directory -- arg1 (LoadError)
$ ruby -- 'arg1' 'arg2' << EE
> puts "args: #{ARGV}"
> EE
ruby: No such file or directory -- arg1 (LoadError)
$ ruby -e << EE
> puts "args: #{ARGV}"
> EE
ruby: no code specified for -e (RuntimeError)
$

I do not know how to pass parameters in this situation. The -e option doesn't get what's passed to STDIN. According to man page, the syntax is:

ruby ... [--] [prog_file] [args]

but my prog_file is on STDIN.

Upvotes: 4

Views: 1370

Answers (2)

Stefan
Stefan

Reputation: 114178

Like many other Unix utilities, ruby recognizes - as a special filename for STDIN:

$ echo "p ARGV" | ruby - foo bar
["foo", "bar"]

or:

$ ruby - foo bar << EE
> p ARGV
> EE
["foo", "bar"]

or: (pressing controlD to end the input)

$ ruby - foo bar
p ARGV
["foo", "bar"]

Upvotes: 2

Santhosh
Santhosh

Reputation: 29124

You can pass parameters like this

ruby << EE "" arg1 arg2
> puts ARGV.inspect
> EE
# ["arg1", "arg2"]

The "" is for a ruby file path, or in this case - empty.

Upvotes: 3

Related Questions