首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >OptParser不返回选项

OptParser不返回选项
EN

Stack Overflow用户
提问于 2014-04-20 20:12:49
回答 1查看 46关注 0票数 1

我有一个代码示例:

代码语言:javascript
复制
#!/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] = var类中定义的OptParser。我想在我的程序中使用-v--version使它更像unix。

我在用ruby-2.0

更新:我尝试用workswhen options[:version]更改when "version"的方式对我来说似乎是最好的方法,但是没有什么效果。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-04-20 21:07:45

当你写案例ARGV[0]时,你完全忽略了opt_parser.

ARGV[0]是命令行中的第一个单词。opt_parser的全部要点是你不看ARGV

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23187079

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档