4

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.

1
  • Not enough info, what have you tried already? What does the code look like? Commented Nov 8, 2012 at 17:00

2 Answers 2

12

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"]}
Sign up to request clarification or add additional context in comments.

5 Comments

Is optparse "part" of Ruby, or something I have to download/install?
part of the standard library. built in.
+1: Thx for the suggestion. I think I'm going to go with @Anthony Alberto's suggestion, but this is good to have in my toolbox. ruby_knowledge += 0.1
this way is much more robust if you plan to pass multiple arguments for sure, but his should work fine if you only plan to pass the one array.
After reading the documentation and playing with optparse, I actually went with this solution. It turns out to be much better, even for my simple needs. Nonetheless, I have learned much from both replies -- thanks.
3

If you're using bash as your terminal, this should work :

integer_array = ARGV[0].scan(/\d/).map(&:to_i) # => Array containing 1,2,3

Tried it with zsh and it crashes, because zsh tries to interpret the [] on the command line though

For zsh, you'd have to use

foobar.rb "[1,2,3]"

2 Comments

I'm actually using Windows, but I will try working with this.
In IRB under Windows, this actually returns an array of string, rather than int, but hey that's probably close enough.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.