【问题标题】:In Ruby, getoptlong destructively parses ARGV. Is there a way around this?在 Ruby 中,getoptlong 会破坏性地解析 ARGV。有没有解决的办法?
【发布时间】:2008-12-01 03:58:00
【问题描述】:

我需要多次调用 getoptlong,但在第一次 ARGV 为空之后。

【问题讨论】:

    标签: ruby getopt


    【解决方案1】:

    在第一次调用之前捕获参数,完成后将它们放回去。不过,听起来你在做一些奇怪的事情。

    编辑:(展开)

    这里有很多复制和粘贴。我认为这有助于清晰:

    require 'getoptlong'
    
    storage = ARGV.clone
    
    opts = GetoptLong.new(
      ['--help', '-h', GetoptLong::NO_ARGUMENT ],
      [ '--repeat', '-n', GetoptLong::REQUIRED_ARGUMENT ],
      [ '--name', GetoptLong::OPTIONAL_ARGUMENT ]
    )
    
    puts "Before: #{ARGV.inspect}"
    opts.each { |opt, arg| puts "Parsed #{opt} = #{arg}" }
    puts "After: #{ARGV.inspect}"
    
    # Copy
    storage.each {|x| ARGV << x }
    
    opts = GetoptLong.new(
      ['--help', '-h', GetoptLong::NO_ARGUMENT ],
      [ '--repeat', '-n', GetoptLong::REQUIRED_ARGUMENT ],
      [ '--name', GetoptLong::OPTIONAL_ARGUMENT ]
    )
    
    puts "Before 2: #{ARGV.inspect}"
    opts.each { |opt, arg| puts "Parsed #{opt} = #{arg}" }
    puts "After 2: #{ARGV.inspect}"
    

    【讨论】:

    • 不太好用。我在类构造函数中调用 getoptlong 。我在一个文件中多次对此类(ruby 的 TestUnit 框架)进行子类化。在方法中重新定义 ARGV 会在 Ruby 中产生错误
    • 你不需要重新定义它。我会展开的。
    • 太棒了。我希望你的实际代码比我这里的重用更多。 :)
    猜你喜欢
    • 1970-01-01
    • 2012-08-21
    • 2023-02-03
    • 1970-01-01
    • 2016-11-19
    • 2023-04-01
    • 1970-01-01
    • 2020-02-01
    • 1970-01-01
    相关资源
    最近更新 更多