Crystal の OptionParser を試してみる。
class OptionParser
http://crystal-lang.org/api/index.html#http%3A//crystal-lang.org/api/OptionParser.html
まずはプロジェクトを作成。
% crystal init app hello
% cd hello
% vim src/hello.cr
内容は以下。
require "./hello/*"
require "option_parser"
name = "World"
times = 1
OptionParser.new do |opt|
opt.on("-n NAME", "--name=NAME", "name option") { |v| name = v }
opt.on("-t TIMES", "--times=TIMES", "times option") { |v| times = v }
end.parse!
times.to_i.times {
puts "Hello, #{name}"
}
ほとんど Ruby の optparse と同じだけど on
の第3引数 description
が省略できないっぽい。
https://github.com/manastech/crystal/blob/42efdbf797349d70c1e2e4c0ece607c6ed419077/src/option_parser.cr#L42-L51
ビルドして実行。
% crystal build src/hello.cr
% ./hello
Hello, World
% ./hello --name=Foo --times=3
Hello, Foo
Hello, Foo
Hello, Foo
% ./hello -n Bar -t 2
Hello, Bar
Hello, Bar