0

This is my code:

#!/usr/bin/env ruby
# OptionParser
require 'optparse'

options = {}
optparse = OptionParser.new do|opts|
    opts.banner = '...'

    # This option inputs ...
    options[:Lap1] = []
    opts.on('-1', '--Lap1 filepath1,width1,height1,a1,first1,last1', String, '...') do|l1|
        options[:Lap1] = l1.split(',')  
    end
end
optparse.parse!

My goal is to have an array of the separate inputs separated by commas. However this code only outputs the first variable $filepath1.

The output of:

puts(options[:Lap1])

and

puts(options[:Lap1][0]

is just the the first variable filepath1.

puts(options[:Lap1][1])

is nil, when it should be the variable width1.

Any suggestions or potential fixes would be helpful, thank you.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Blaid
  • 1
  • 1

2 Answers2

0

You need to call the parse! method on your OptionParser object after declaring all the options.

optparse.parse!
philant
  • 34,748
  • 11
  • 69
  • 112
0

I'd write that code a bit differently:

require 'optparse'
require 'pp'

options = {
  :Lap1 => []
}

optparse = OptionParser.new do |opts|
  opts.banner = '...'

  # This option inputs ...
  opts.on(
    '-1', '--Lap1 filepath1,width1,height1,a1,first1,last1',
    Array,
    '...'
  ) { |l1| options[:Lap1] = l1 }
end.parse!
pp options

Running that at the command-line:

ruby test.rb -1 filepath1,width1,height1,a1,first1,last1

Results in:

{:Lap1=>["filepath1", "width1", "height1", "a1", "first1", "last1"]}

Testing using --Lap1 results in:

ruby test.rb --Lap1 filepath1,width1,height1,a1,first1,last1

And:

{:Lap1=>["filepath1", "width1", "height1", "a1", "first1", "last1"]}

In my opinion, you should set your defaults when you define your options hash.

options = {
  :Lap1 => []
}

Also, notice the use of Array instead of String. OptionParser will automatically split a comma-delimited string into an array of individual elements if you use Array, saving you that split step, and avoiding a bit of confusing code. See the documentation for OptionParser's make_switch method for more information.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
  • So, I still get the same error even when doing it that way. It only seems to read the first variable. – Blaid Sep 10 '13 at 22:03
  • Well, I don't know how you're calling the code from the command-line because you didn't say. The command-lines above work correctly with the code I gave. – the Tin Man Sep 10 '13 at 22:16
  • I ran it exactly like that. It was working a couple days ago, but now I keep running into this problem. – Blaid Sep 10 '13 at 22:37
  • Then you have something that changed on your system. The command-line given is valid and correct. Confirm your Ruby version is correct. – the Tin Man Sep 10 '13 at 22:48