【发布时间】: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