LoginSignup
48
49

More than 5 years have passed since last update.

Rubyのoptparseを軽く使うなら悩む必要なんてなかった

Posted at

今回『スクリプトに--dry-runオプションのみを作りたい』場面が個人的に出てきました。
以前、Rubyのoptparseを軽く使いたい時に悩むというような事を書いていたのですが、実は軽く使いたい時は悩む必要がなかったのでメモ・・・orz

概要

library optparse

ARGV の機能
optparse を require すると ARGV に OptionParser::Arguable の機能 が加わります。以下の書き方ができるようになります。
OptionParser::Arguable#getopts はオプションを保持した Hash を返します。

# sample.rb の内容
require 'optparse'
params = ARGV.getopts("a:c:", "foo", "bar:")
p params

この sample.rb を実行すると

$ ruby sample.rb -a 1 --foo --bar xxx
{"a"=>"1", "c"=>nil, "foo"=>true, "bar"=>"xxx"}

(引用元のコードでは、getopts第一引数のa:の後ろはb:なのですが、そうするとQiitaの記法に引っかかるのか、"a:b:"と絵文字っぽくなってしまうので、cに変更しました。)

試しに上記スクリプトを--helpをしてみると

$ ruby sample.rb --help
Usage: sample [options]
    -a VAL
    -c VAL
        --foo
        --bar VAL

・・・素敵やん。

なおgetoptsに関して、詳しくは以下のリンク
instance method OptionParser::Arguable#getopts

今回のコード

というわけで、今回は--dry-runのオプションのみを作りたかっただけなので、以下に落ち着きました。

require "optparse"

options = ARGV.getopts("", "dry-run")
p options

実行結果

$ ruby temp.rb --dry-run
{"dry-run"=>true}
$ ruby temp.rb
{"dry-run"=>false}

シンプル!!(`・ω・´)

まとめ

ちゃんとドキュメントは読みましょう。。。orz
だいぶ手軽になりましたね〜(^^

48
49
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
48
49