ARGV 循环跳过 Ruby 中的 if 语句

ARGV loop skips if statement in Ruby

在我的脚本中,我使用 ARGV 流来获取命令行参数。有一段代码:

ARGV.each do|a|
item = JSON.parse(%x{curl -X GET https://puppetdb.ai:8081/pdb/query/v4/facts/#{a} --tlsv1 --interface x.x.x.x --cacert certificate.pem --cert certificate-pem.cer --key certificate-privkey.pem})
  item.each do |h|
     arr << {"name" => h['certname'], "#{a}" => h['value'], "environment" => h['environment']}
  end
end

通过 curl,我使用 puppetdb API 获得了一些数据。一切正常,但我想添加一些 if 语句来打印脚本的帮助。看起来像这样:

ARGV.each do|a|
  if (a == "help")
    puts "this is help 4 U"
  else 
    item = JSON.parse(%x{curl -X GET https://puppetdb.ai:8081/pdb/query/v4/facts/#{a} --tlsv1 --interface x.x.x.x --cacert certificate.pem --cert certificate-pem.cer --key certificate-privkey.pem})
      item.each do |h|
         arr << {"name" => h['certname'], "#{a}" => h['value'], "environment" => h['environment']}
      end
  end
end

但脚本会忽略 "help" 并为 curl 填充 "help" 参数。你能帮我解决这个问题吗?

尝试使用 .strip! 并查看 Ruby String class documentation

这些可用于在您遍历 Ruby 命令提供的每个参数时清理输入。最好只使用 ARGV Array 作为 Array 并查看 Ruby Array class documentation 以查看 Ruby 中可用的方法数组数据类型(这是 ARGV 的形式)。例如使用 .include?("help") 的子字符串搜索。尽早使用这些方法文档对于理解 Ruby 为您提供的工具至关重要。