Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing An Array Via Command Line

Tags:

ruby

I have a Ruby script, called foobar.rb, which takes multiple parameters.

I want to (optionally) be able to specify an array of integers on the command line and be able to process them as a single option. I think that my command line would look something like this:

foobar.rb [1,2,3]

On a scale of 1-10 my knowledge of Ruby is probably around a 6. Just enough to know that there's probably an easy way to accomplish this, but not enough to know what it is or even where to look in the docs.

How can I parse this single comma-separated list of integers and end up with an Array in the code? I would prefer an idomatic, 1-liner solution that doesn't require the addition of any external libraries, if such a solution exists.

like image 621
John Dibling Avatar asked Dec 07 '22 11:12

John Dibling


1 Answers

I would use optparse for it myself, like this:

require 'optparse'

options = {}

OptionParser.new do |opts|
  opts.banner = "Usage: #{$0} [options]"

  opts.on("-a", "--argument a,b,c", Array, "Array of arguments") { |a| options[:array] = a.map { |v| v.to_i } }
end.parse!

puts options.inspect

  => {:array=>["1", "2", "3", "4"]}
like image 91
Eugene Avatar answered Dec 17 '22 18:12

Eugene