简体   繁体   中英

ARGV loop skips if statement in Ruby

In my script I use ARGV stream to get command-line arguments. There is a piece of code:

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

With curl I get some data using puppetdb API. It all works fine, bu I've wanted to add some if statement to print help for script. It looks like that:

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

but the script ignore "help" and fills in "help" argument to curl. Can you help me with this?

Try using .strip! and look at the Ruby String class documentation .

These can be used to clean up the input as you iterate through each argument supplied with the Ruby command. It may be better to just use the ARGV Array as an Array and look at the Ruby Array class documentation to see the methods methods available to you in Ruby when using the array datatype (which is the form ARGVs come in).. Such as substring search using .include?("help") . Using these method documentation early on is critical to understanding the tools that Ruby provides you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM