Reputation:
I'm stuck in a totally stupid situation. When I use the snippet below, despite my command line being "./the_script.rb -s serv" and I check the value of the service variable within the code, it's always taken to be of boolean class by optparse. So I cannot get my string from the command line...
any ideas ?
opt = OptionParser.new do |opt|
opt.on('-s','--service','twitter (tw) or identica (id)') do |val|
service = val.to_s
end
end
Upvotes: 1
Views: 570
Reputation: 1050
As you may see in the in code documentation of optparse.rb
(in /usr/local/rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/optparse.rb
for me) under "==== Using Built-in Conversions
", , you have to specify the string of the second argument to the on
method:
173 # ==== Using Built-in Conversions
174 #
175 # As an example, the built-in +Time+ conversion is used. The other built-in
176 # conversions behave in the same way.
177 # OptionParser will attempt to parse the argument
178 # as a +Time+. If it succeeds, that time will be passed to the
179 # handler block. Otherwise, an exception will be raised.
180 #
181 # require 'optparse'
182 # require 'optparse/time'
183 # OptionParser.new do |parser|
184 # parser.on("-t", "--time [TIME]", Time, "Begin execution at given time") do |time|
185 # p time
186 # end
187 # end.parse!
188 #
Thus
opt.on('-s','--service [String]','twitter (tw) or identica (id)') do |val|
Upvotes: 0
Reputation: 40029
I'm a Python programmer, not a Ruby one, but browsing the examples in the Ruby docs for this, I'd say the default behavior as you have it is to act as a boolean. You need to specify more parameters for it to actually store the value.
opts.on("-s", "--service [SERVICE]", [:twitter, :identica], "Select a service (Twitter or Identica)" do |service|
options.service = service
end
Then options.service
should have the designated service. I think... Hey, it's Ruby. ;-)
Upvotes: 2