Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access original command-line argument string in Ruby?

I'm trying to access the original command line argument string in Ruby (ie - not using the pre-split/separated ARGV array). Does anyone know how to do this? For example:

$> ruby test.rb command "line" arguments

I want to be able to tell if 'line' had quotes around it:

"command \"line\" arguments"

Any tips? Thanks in advance

like image 380
Bub Bradlee Avatar asked Jun 03 '10 14:06

Bub Bradlee


People also ask

How do I get command line arguments in Ruby?

In your Ruby programs, you can access any command-line arguments passed by the shell with the ARGV special variable. ARGV is an Array variable which holds, as strings, each argument passed by the shell.

How do I access command line arguments?

To pass command line arguments, we typically define main() with two arguments : first argument is the number of command line arguments and second is list of command-line arguments. The value of argc should be non negative. argv(ARGument Vector) is array of character pointers listing all the arguments.

What is * args in Ruby?

In the code you posted, *args simply indicates that the method accepts a variable number of arguments in an array called args . It could have been called anything you want (following the Ruby naming rules, of course).

Are command line arguments string?

Each argument on the command line is separated by one or more spaces, and the operating system places each argument directly into its own null-terminated string. The second parameter passed to main() is an array of pointers to the character strings containing each argument (char *argv[]).


1 Answers

As far as I can tell, ruby is not removing those double-quotes from your command line. The shell is using them to interpolate the contents as a string and pass them along to ruby.

You can get everything that ruby receives like this:

cmd_line = "#{$0} #{ARGV.join( ' ' )}"

Why do you need to know what is in quotes? Can you use some other delimiter (like ':' or '#')?

If you need to, you can pass double-quotes to ruby by escaping them:

$> ruby test.rb command "\"line\"" arguments

The above cmd_line variable would receive the following string in that case:

test.rb comand "line" arguments
like image 144
irkenInvader Avatar answered Dec 07 '22 05:12

irkenInvader