What's the point of ARGV in Ruby?

后端 未结 5 927
旧巷少年郎
旧巷少年郎 2020-12-06 03:31

What\'s the point of ARGV in Ruby?

first, second, third = ARGV 
puts \"The script is called: #{$0}\"
puts \"Your first variable is: #{first}\"
puts \"Your se         


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-06 04:32

    ARGV has a long tradition and comes from the UNIX/POSIX world where most C programs must contain the following:

    int main(int argc, char **argv)
    {
       return(0);
    }
    

    There argc represents the number of arguments supplied, and argv is a low-level pointer to the first of potentially a number of string pointers. The name argv has stuck around in various forms.

    Command-line arguments are very popular with developers, though they're usually not used quite as you seem to think. Un-named arguments are much harder to deal with. That's why things like optparse exist to help deal with them.

    Here's an example from the OptionParser documentation:

    require 'optparse'
    
    options = {}
    OptionParser.new do |opts|
      opts.banner = "Usage: example.rb [options]"
    
      opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
        options[:verbose] = v
      end
    end.parse!
    
    p options
    p ARGV
    

    This allows you to define much more usable command-line arguments and then use them. For your example, I'd expect it to work like this:

    test_script --live "New York" --computer "Lenovo" --like
    

    That makes it quite obvious what the arguments are because they're named.

提交回复
热议问题