Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

optionparser pass an array to ruby file

I have a trouble with passing an arguments to my ruby file. IE,

OptionParser.new do |opts|
  opts.banner = 'Usage: mp3split.rb [options]'

  opts.on('-f', '--filename fName1,fName2,fName3', Array, 'absolute or relative pathes to file') { |f| options[:filenames] = f }
end.parse!

This approach requires me to write this commands:

ruby mp3split.rb --filename fursov_13.mp3,fursov_14.mp3,fursov_14_2.mp3,fursov_15.mp3,fursov_16.mp3,fursov_17.mp3

But I want to get array by this:

ruby mp3split.rb --filename fursov_13.mp3 fursov_14.mp3 fursov_14_2.mp3 fursov_15.mp3 fursov_16.mp3 fursov_17.mp3

How can I implement this functionality? I can't find anything helpful about this in docs.

like image 979
asiniy Avatar asked Jun 26 '26 05:06

asiniy


1 Answers

With OptionParser you can’t. There is a workaround, though, when there is the only list you need to handle that way and you won’t pass other arguments to the script. OptionParser splits the input by spaces before it processes it. The unkeyed arguments remain in ARGV global constant after parsing. Assuming everything described above is met, here we go:

OptionParser.new do |opts|
  options[:filenames] = []
  opts.banner = 'Usage: mp3split.rb [options]'        
  opts.on('-f', '--filename fName1 fName2 fName3', Array, 
          'absolute or relative pathes to file') do |f|
    options[:filenames] |= [*f]
  end
end.parse!

options[:filenames] |= ARGV

I apparently fixed another glitch within your code: options[:filenames] should be appended not overwritten on every occurence of -f switch, OptionParser supports script -f f1 -f f2 -f f3.

like image 154
Aleksei Matiushkin Avatar answered Jun 28 '26 18:06

Aleksei Matiushkin