LoginSignup
7
7

More than 5 years have passed since last update.

Crystal の OptionParser

Last updated at Posted at 2015-07-26

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
7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7