1

我有这个代码示例:

#!/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哈希是空的。就像它不接受options[:var] = varOptParser 类中定义的一样。我想在我的程序中使用-vand--version使它更像 unix。

我正在使用ruby-2.0.

更新:它是works我尝试更改的代码的方式when "version"when '-v'或者when options[:version]对我来说似乎是最好的方法,但没有任何效果。

4

1 回答 1

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
于 2014-04-20T21:07:45.760 回答