16
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Ruby] Slopの使い方

Last updated at Posted at 2013-12-14

コマンドラインからのオプションをパースしてくれるSlopの使い方。
gemでインストールができる。

gem install slop

使い方はSlop.parse do ... endSlopのインスタンスを作って、後はそのインスタンスを経由してオプションの有無などを確認することができる。

slop_sample.rb
require 'slop'

opts = Slop.parse do
	banner 'Usage: slop_sample.rb [options]'

	on 'name=', 'Your name'
	on 'p', 'password', 'An optional password', argument: :optional
	on 'v', 'verbose', 'Enable verbose mode'
end

p opts.verbose?
p opts.v?
p opts.password?
p opts[:name]
p opts.to_hash
$ ruby slop_sample.rb  -v --name yui
# =>
true   (opts.verbose?)
true   (opts.v?)
false  (opts.password?)
"yui"   (opts[:name])
{:name=>"yui", :password=>nil, :verbose=>true}   (opts.to_hash)

Slop.parse do ... endに渡すブロックには引数としてSlopのインスタンスを渡すことも可能で、そのときは次のような書き方になる。

slop_sample.rb
require 'slop'

opts = Slop.parse do |opt|
	opt.banner 'Usage: slop_sample.rb [options]'

	opt.on 'name=', 'Your name'
	opt.on 'p', 'password', 'An optional password', argument: :optional
	opt.on 'v', 'verbose', 'Enable verbose mode'
end

Slop.parse:help => trueを渡すと-h--helpでヘルプを出力できるようになる。

slop_sample.rb
require 'slop'

opts = Slop.parse(help: true) do |opt|
	opt.banner 'Usage: slop_sample.rb [options]'

	opt.on 'name=', 'Your name'
	opt.on 'p', 'password', 'An optional password', argument: :optional
	opt.on 'v', 'verbose', 'Enable verbose mode'
end
$ruby slop_sample.rb  -h
# =>
Usage: slop_sample.rb [options]
        --name          Your name
    -p, --password      An optional password
    -v, --verbose       Enable verbose mode
    -h, --help          Display this help message.
16
14
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
16
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?