cvoep28
cvoep28

Reputation: 423

How to pass array as argument inside ARGV

I have a ruby script that takes two inputs for ARGV. The second input is an array of files. I'm having trouble iterating through the file array passed to ARGV. Here is what I have so far:

arg1, FILES = ARGV

FILES.each do |fname| 
    #do something with fname 
end 

I'm running my script from the command line like this:

ruby myScript.rb arg1 ['path/to/file1.jpg', '/path/to/file2.jpg'] 

And I'm getting the following error:

zsh: bad pattern: [path/to/file1.jpg,

Enclosing the array argument in single quotes like this:

ruby myScript.rb arg1 '['path/to/file1.jpg', '/path/to/file2.jpg']'

Produces a different error, as it interprets it as a String rather than array.

How can I accomplish this correctly?

Upvotes: 2

Views: 2164

Answers (4)

Jacob Brown
Jacob Brown

Reputation: 7561

arg1, _files = ARGV
files = eval(_files)
files.each { |f| ... }

But there are reasons to not use eval (see Is 'eval' supposed to be nasty?).

You might pass the files list as a json string and then do JSON.parse on it to be safer, e.g.:

require 'json'
arg1, _files = ARGV
files = JSON.parse(_files)
files.each { |f| ... }

#> ruby myScript.rb arg1 '["path/to/file1.jpg", "/path/to/file2.jpg"]'

Upvotes: 0

dimid
dimid

Reputation: 7631

You can either split manually, e.g. arg, arr = ARGV[0], ARGV[1..-1] or use the splat operator arg, *arr = ARGV

Upvotes: 1

ndnenkov
ndnenkov

Reputation: 36101

Use

arg1, *FILES = ARGV

and don't place any brackets or commas during invocation:

ruby myScript.rb arg1 file1 file2 file3


EDIT: If you want to add another argument, you can do:

arg1, arg2, *FILES = ARGV

or

arg1, *FILES, arg2 = ARGV

Upvotes: 2

mipadi
mipadi

Reputation: 410582

You can't pass an array as a command-line argument. All arguments are passed as strings.

But given your code, you could just pass the arguments like this:

$ ruby myScript.rb arg1 path/to/file1.jpg /path/to/file2.jpg

And then, change your first line of code to this:

arg1, *FILES = ARGV

And after, arg1 = 'arg1' and FILES = ['path/to/file1.jpg', 'path/to/file2.jpg'].

Upvotes: 1

Related Questions