我有这个代码示例:
#!/usr/bin/env ruby
require_relative File.expand_path('../../lib/argosnap', __FILE__)
require 'optparse'
options = {}
opt_parser = OptionParser.new do |opt|
opt.banner = "argosnap #{Argosnap::VERSION} ( http://github/atmosx/argosnap )\nUsage: argosnap [OPTIONS]"
opt.separator ""
opt.separator " version: dislay version"
opt.separator " install: installs 'config.yml' and launchd script"
opt.separator " balance: check picodollars"
opt.separator ""
opt.on("-v","--version","display version") do |version|
options[:version] = version
end
opt.on("-c","--config [TYPE]", String, "install configuration files") do |config|
options[:config] = config
end
opt.on("-b","--balance","executes 'argosnap' and displayes notifications") do |balance|
options[:balance] = balance
end
opt.on("-h","--help","help") do
puts opt_parser
end
end
begin
opt_parser.parse!
rescue OptionParser::InvalidOption => e
puts "No such option! Type 'argosnap -h' for help!"
exit
end
case ARGV[0]
when "version"
puts Argosnap::VERSION
when "config"
Argosnap::Install.new.config
when "balance"
b = Argosnap::Fetch.new.balance
puts "Current balance (picodollars): #{b}"
else
puts "Type: 'argosnap -h' for help!"
end
我的问题是options
哈希是空的。如果它不接受OptParser类中定义的options[:var] = var
,就好了。我想在我的程序中使用-v
和--version
来使其更像unix。
我正在使用ruby-2.0
。
更新:代码works
的方式我尝试用when "version"
或when '-v'
更改when options[:version]
这对我来说似乎是最好的方法,但没有工作
答案 0 :(得分:1)
当您撰写案例ARGV[0]
时,您完全忽略了opt_parser ...
ARGV[0]
是命令行中的第一个单词。 opt_parser的重点是你不要看ARGV
:
if options[:version]
puts Argosnap::VERSION
elsif options[:config]
Argosnap::Install.new.config
elsif options[:balance]
b = Argosnap::Fetch.new.balance
puts "Current balance (picodollars): #{b}"
else
puts "Type: 'argosnap -h' for help!"
end