【问题标题】:Accessing Ruby hash value via symbol key returning true not value通过返回 true 而非值的符号键访问 Ruby 哈希值
【发布时间】:2021-06-11 07:21:21
【问题描述】:

我正在尝试使用命令行参数制作一个基本的命令行工具(从简单开始逐步构建)。我正在使用 Ruby 及其 OptionParser 类来执行此操作。我有以下代码:

require 'optparse'

options = {}

OptionParser.new do |option|
  option.banner = "Usage: todo_list.rb <list title> <tasks>"
  
  option.on("-t", "--title", "Title of task list") do |value|
    options[:title] = value
  end 

  option.on("-c", "--content", "Content of task list (tasks)") do |value|
    options[:content] = value
  end 
  
  option.on("-h", "--help", "Show this help message") do ||
    puts option
  end
end.parse!

p options
p ARGV

if options[:title]
  puts "Created task list with title: #{ options[:title] }"
end

if options[:content]
  puts "Added task: #{ options[:content] }"
end

作为参考,我一直在运行 clt 作为 todo_list.rb -t Test -c 内容。

在最后 2 个 if 语句中,我只是尝试访问选项哈希中的键 :content/:title 的值(如果它们存在)(如果它们已从命令行传递),但程序仅返回 true ("Created task list with title true") / ("Added task: true"),而不是值("Test" or "content")

我认为,使用 p ARGV 输出 ['Test', 'Content'] 以便正确传递参数。使用 p 选项返回 {:title=>true, :content=>true}。

我不知道为什么会这样。如果有人有线索,任何和所有的建议都会受到赞赏。谢谢。

【问题讨论】:

标签: ruby command-line command-line-arguments


【解决方案1】:

您需要告诉选项解析器您的开关需要参数:

option.on("-tTITLE", "--title TITLE", "Title of task list") do |value|
  options[:title] = value
end 
option.on("-cCONTENT", "--content CONTENT", "Content of task list (tasks)") do |value|
  options[:content] = value
end 

否则选项被认为是简单的布尔标志。

optparse 的文档在 #make_switch 部分对此进行了介绍:

https://ruby-doc.org/stdlib/libdoc/optparse/rdoc/OptionParser.html#method-i-make_switch

但这并不完全显而易见,除非您已经知道要查找的内容。您通常会通过查看示例和实验来弄清楚它是如何工作的,然后您会偶然发现#make_switch 方法。

【讨论】:

    猜你喜欢
    • 2014-04-09
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    • 2019-10-24
    • 2014-11-22
    • 1970-01-01
    • 2021-11-15
    • 2011-06-30
    相关资源
    最近更新 更多