1
0
Fork 0
mirror of https://github.com/ruby/ruby.git synced 2022-11-09 12:17:21 -05:00

[ruby/optparse] Tutorial: explain custom argument converters (https://github.com/ruby/optparse/pull/19)

385dd4322d
This commit is contained in:
Burdette Lamar 2021-04-11 23:43:02 -05:00 committed by Hiroshi SHIBATA
parent bf175e7ec2
commit a15f0b9fe2
No known key found for this signature in database
GPG key ID: F9CF13417264FAC2
4 changed files with 83 additions and 4 deletions

View file

@ -345,8 +345,14 @@ Executions:
=== Custom Argument Converters
You can create custom argument converters.
To create a custom converter, call OptionParser#accept with a class argument,
along with a block that converts the argument and returns the converted value.
To create a custom converter, call OptionParser#accept with:
- An identifier, which may be any object.
- An optional match pattern, which defaults to <tt>/.*/m</tt>.
- A block that accepts the argument and returns the converted value.
This custom converter accepts any argument and converts it,
if possible, to a \Complex object.
:include: ruby/custom_converter.rb
@ -360,3 +366,15 @@ Executions:
[(1+2i), Complex]
$ ruby custom_converter.rb --complex 0.3-0.5i
[(0.3-0.5i), Complex]
This custom converter accepts any 1-word argument
and capitalizes it, if possible.
:include: ruby/match_converter.rb
Executions:
$ ruby match_converter.rb --capitalize foo
["Foo", String]
$ ruby match_converter.rb --capitalize "foo bar"
match_converter.rb:9:in `<main>': invalid argument: --capitalize foo bar (OptionParser::InvalidArgument)