👋

optparseの使い方

に公開

optparseでオプションを指定してRubyプログラムを実行できるようにしました。
optparseの使い方を整理しておこうと思い記事にすることにしました。
下記の記事を参考にしました。
https://docs.ruby-lang.org/ja/latest/library/optparse.html

いろいろ呼び出し

sample.rb
require 'optparse'

opt = OptionParser.new
opt.on('-a') {|v| p v}
opt.parse!(ARGV)
p ARGV
オプションなしの実行結果
ruby sample.rb        
[]
オプション付きの実行結果
ruby sample.rb -a 
true
[]
オプション付き引数ありの実行結果
ruby sample.rb -a test!
true
["test!"]
オプション付き引数複数ありの実行結果
ruby sample.rb -a test1 test2 test3
true
["test1", "test2", "test3"]

OptionParser#parse!実行前後でのARGVの変化

sample.rb
require 'optparse'

opt = OptionParser.new

opt.on('-a') { p 'test!' }
p ARGV
opt.parse!(ARGV)
p ARGV

実行結果を確認するとわかる通り、parse!実行後にはオプション(-a)が配列から削除されています。
また、parse!実行のタイミングでブロック内の処理が実行されます。

実行結果
ruby sample.rb -a test!
["-a", "test!"]
"test!"
["test!"]

Discussion