OptParse不返回选项

时间:2014-04-20 20:12:49

标签: ruby optionparser

我有这个代码示例:

#!/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]这对我来说似乎是最好的方法,但没有工作

1 个答案:

答案 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