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.
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"]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With