Ruby Stdlib Learning--optionparser

Source: Internet
Author: User

Http://ruby-doc.org/stdlib-2.3.3/libdoc/optparse/rdoc/OptionParser.html#method-c-new read Lib's documentation and make a note. Optionparser This class is used to set command line parameter options when writing commands on the Lines tool. Getoptlong has similar features, but it is recommended to use Optionparser. Example: A simple example (mainly into a door, by the way to demonstrate the next option without parameters how to handle, like-V,-F type))
1 #save directly to TEST.RB, run Ruby Test.rb-v somethingnouse to run properly2 #run Ruby Test.rb-v somethingnouse-s because there is no option to set-S to handle,3 #will error "invalid option:-S (optionparser::invalidoption)"4Require'Optparse'5  6P ARGV#= = ["-V", "somethingnouse"]7options = {}#self-set to receive input parameters of the hash, with an array should also be able, casually,8              #It's nothing to do with Optionparser.9Optionparser.new do |opts|TenOpts.banner ="Usage:example.rb [Options]" One   AOpts.on ("- v","--[no-]verbose","Run verbosely") Do |v|#Option-V does not have a value, and it appears to be assigned a value of true -Puts"Value of v"#without writing the-v option, the program is not at all in this line and can be understood as if has "-V" feel it -Puts V#= True theOptions[:verbose] = V#here to write some functional code - End -end.parse!#shift a parameter, code:a = [A.shift], a=[2,3] should be similar to this mechanism, the details did not see -   +P Options#{: verbose=>true} -P ARGV#["Somethingnouse"]
View CodeSecond, example: Generate Help is basically the side of debugging side note to learn. On the basis of the example in the document, some small places are changed to be used for debugging.
1Require'Optparse'2  3Options =struct.new (: Name)4  5 classParser6   defself.parse (Options)7args = Options.new (" World")#parameter of struct class args name default value is "World"8  9Opt_parser = optionparser.new do |opts|#start using Optionparser class processing parametersTenOpts.banner ="Usage:example.rb [option]" #output Help when the top row One   AOpts.on ("- N NAME","--name=name","Name to say hello to") Do |n| -       #parameter name is required when the input parameter option is-N, usage: Ruby test.rb--name= "A puppy" -       #examples of-nname between no space, measured the parameters written "-ndog" is useful.  the       #Similarly, the long parameter--name is written as--name name, while the Ruby test.rb--name= "A Puppy" is also established when called, very flexible -Args.name = n#This is actually the value of the parameter to other places, processing, printing, whatever you do with - puts N -Puts"#{argv}" #can use the case to look at the changes in argv, command for the Ruby test.rb-n dog-h runtime, here output ["-H"] +                        #It's a bit out of the way , and there's time to see Optionparser code in-depth understanding. - End +   AOpts.on ("- H","--help","Prints This Help") do atPuts opts#Print all the OPTs content, in fact, we set each of the Opt.on plus banner -         #exit #打印完help就退出了, no other parameters are processed. Note that exit is the exit program -         #For example, I printed the value of name in Line17. If I run Ruby test.rb-n dog-h -         #Output: -         #Dog -         #Usage:example.rb [option] in         #-N,--name=name name to say hello to -         #-H,--help Prints this Help to         #It is obvious that the-N option is processed first, and then the-H again exits . +   - End the End *   $opt_parser.parse! (options)#! =>shift continue with the next parameterPanax Notoginseng     returnArgs#see here to understand that in practical applications, you can use this struct to collect all incoming parameter values - End the End +   A #options = Parser.parse%w[-h] #%w is used to denote an array in which the elements are quoted, and the elements are separated by spaces. e.g.%w[a b] = ["A", "B"] theoptions = Parser.parse ARGV#Direct processing of parameters passed in from the Run command line +Puts options
View CodeBy the way. Ruby's options Source: That's what Ruby--help lists: https://github.com/ruby/ruby/blob/ruby_2_3/ruby.c It seems that there is no library or the like (the main hug for a glance without looking at the include<getopt.h>), should be a direct macro +printf (these lines of code position line224-237):
1 #defineSHOW (M) Show_usage_line ((m). Str, (m). Namelen, (m). Secondlen, Help)2printf"Usage:%s [Switches] [--] [programfile] [arguments]\n", name);3  for(i =0; i < num; ++i)4 SHOW (Usage_msg[i]);5 if(!HELP)return;6  for(i =0; I < numberof (help_msg); ++i)7 SHOW (Help_msg[i]);8Puts"Features:");9  for(i =0; I < Numberof (features); ++i)Ten SHOW (Features[i]); One}
View CodeDefining a function with a macro I'm basically 0. Have an interest in observing. Three, parameters have some built-in types can be directly used date–anything accepted by date.parsedatetime–anything accepted by Datetime.parsetime–anything Acce Pted by Time.httpdate or time.parseuri–anything accepted by uri.parseshellwords–anything accepted by SHELLWORDS.SHELLW Ordsstring–any non-empty stringinteger–any Integer. would convert octal. (e.g. 124,-3, 040) Float–any float. (e.g, 3.14, -100E+13) Numeric–any integer, float, or rational (1, 3.4, 1/3) Decimalinteger-like integer, but no octal format. Octalinteger-like Integer, but no decimal format. Decimalnumeric--Decimal integer or float. Trueclass–accepts ' +, yes, true,-, no, false ' and defaults as truefalseclass–same as Trueclass, but defaults to False Array–strings separated by ', ' (e.g.) regexp–regular expressions. Also includes options. An example of using time:
1Require'Optparse'2Require'Optparse/time'3  4Optionparser.new do |parser|5   #The example is relatively simple, the emphasis should be on the third parameter, after the input related classes will automatically parse? 6Parser.on ("- T","--time [TIME]", Time,"Begin execution at given time") Do |time|7 p Time8 End9 end.parse!Ten #such as running: Ruby Test.rb-t 2000-1-1 One #output:2000-01-01 00:00:00 +0800 A #time is automatically processed.
View CodeFour op.accept usage. Understand that you can associate an instance of any custom type with accept, and then interact with the outside world through Optionparser. This example, in the documentation, can be associated with the use of the gem install. For example: Gem install Liba. Gem to query the installation path for Liba, each lib and installation path is the relationship between key and value. If you can't find this liba, of course, it will be an error. First of all, understand. Not yet commented, ready to be sorted.
1Require'Optparse'2  3User =struct.new (: ID,: Name)4  5 deffind_user ID6Not_found =->{Raise "No User Found for ID #{id}" }7[User.new (1,"Sam"),8User.new (2,"Gandalf")].find (not_found) do |u|9U.id = =IDTen End One End A   -OP =optionparser.new -Op.accept (User) do |user_id| the Find_user user_id.to_i - End -Op.on ("--user ID", User) do |user| - puts user + End -op.parse!

Ruby Stdlib Learning--optionparser

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.