【问题标题】:How can I get info from user with OptionParser in Ruby?如何在 Ruby 中使用 OptionParser 从用户那里获取信息?
【发布时间】:2020-10-03 20:41:38
【问题描述】:

例如,当我在命令行中输入ruby file.rb -a "water the plants" 我希望将此行添加到哈希中。比如待办事项清单。 所以它看起来像item1: water the plants 这是我到目前为止所做的:

require 'optparse'

option_parser = OptionParser.new do |opts|
    opts.on '-a', '--add', 
end          

提前致谢!

【问题讨论】:

    标签: ruby optparse


    【解决方案1】:

    仔细查看OptionParser 文档中的示例。

    要接受一个参数的,您必须在opts.on 的第二个参数中指定它,如下所示:

    require 'optparse'
    option_parser = OptionParser.new do |opts|
        opts.on '-a', '--add val' do |value|
          puts value
        end
    end.parse!
    

    要使其成为必需参数,只需将 val 更改为大写的 VAL(可以是任何单词,我只是使用“val”作为示例)。

    调用它,你可以看到它是如何工作的:

    ruby file.rb -a "water the plants"
    # => "water the plants"
    
    ruby file.rb -a "water the plants" "do the dishes"
    # => "water the plants"
    
    ruby file.rb -a "water the plants" -a "do the dishes"
    # => water the plants
    # => do the dishes
    

    如您所见,要传递多个值,您需要多次包含-a 标志。为每个值单独调用该块。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-29
      • 2020-05-22
      • 1970-01-01
      • 2014-11-18
      • 2020-07-08
      • 1970-01-01
      • 2019-04-06
      • 2014-09-16
      相关资源
      最近更新 更多