OptParse - how do I get the argument values?

I am trying to use OptParser to get the values of my options, but in the
blocks I only seem to get boolean values.

options = {}
opt_parser = OptionParser.new do |opts|
opts.on(’-h’, ‘–help’, ‘Help’) { usage() }
opts.on(’-a’, ‘–app’, ‘iOS Application’) { |v| options[:app_name] = v
}
opts.on(’-v’, ‘–ios_version’, ‘iOS Version’) { |v|
options[:ios_version] = v }
opts.on(’-p’, ‘–assets_path’, ‘assets_path’) { |v|
options[:assets_path] = v }
opts.on(’-s’, ‘–sim_path’, ‘sim_path’) { |v| options[:sim_path] = v }
end.parse!

options.keys.each do |key|
puts 'key is ’ + key.to_s
puts 'value is ’ + options[key].to_s
end

For the command line
sync_simulator.rb --app angry --assets_path /Users/paul/worms
–ios_version 7.0

The output is
key is ios_version
value is true
key is assets_path
value is true
key is app_name
value is true

I am hoping to get
key is ios_version
value is 7.0
key is assets_path
value is /Home/paul/worms
key is app_name
value is angry

On 2013-09-23, at 5:26 AM, Paul W. [email protected] wrote:

opts.on(’-p’, ‘–assets_path’, ‘assets_path’) { |v|
sync_simulator.rb --app angry --assets_path /Users/paul/worms
I am hoping to get
key is ios_version
value is 7.0
key is assets_path
value is /Home/paul/worms
key is app_name
value is angry

You need to indicate to OptParser that you expect an argument, otherwise
it returns true to say “I saw that option on the command line”. This can
be done by adding a token to the long flag (for more detail see
http://ruby-doc.org/stdlib-2.0.0/libdoc/optparse/rdoc/OptionParser.html
and the example there).

#!/usr/bin/env ruby

require ‘optparse’

options = {}
opt_parser = OptionParser.new do |opts|
opts.on(’-h’, ‘–help’, ‘Help’) { usage() }
opts.on(’-a’, ‘–app NAME’, ‘iOS Application’) {
|name| options[:app_name] = name
}
opts.on(’-v’, ‘–ios_version VERSION’, ‘iOS Version’) { |version|
options[:ios_version] = version
}
opts.on(’-p’, ‘–assets_path PATH’, ‘assets_path’) { |path|
options[:assets_path] = path
}
opts.on(’-s’, ‘–sim_path PATH’, ‘sim_path’) { |path|
options[:sim_path] = path
}
end.parse!

options.each_pair do |key, value|
puts “key is #{key}”
puts “value is #{value}”
end

END

ratdog:tmp mike$ ./try.rb --app angry --assets_path /Users/paul/worms
–ios_version 7.0
key is app_name
value is angry
key is assets_path
value is /Users/paul/worms
key is ios_version
value is 7.0

Hope this helps,

Mike

Mike S. [email protected]
http://www.stok.ca/~mike/

The “`Stok’ disclaimers” apply.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs