通过返回 true 而不是值的符号键访问 Ruby 哈希值

Accessing Ruby hash value via symbol key returning true not value

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

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 as todo_list.rb -t Test -c content.

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

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

我不知道为什么会这样。如果有人有线索,我们将不胜感激任何和所有建议。谢谢。

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

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 方法。