32
33

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.

OptionParserでコマンドライン引数を解析する。

Posted at
use_optionparser.rb
# !/usr/bin/env ruby
# -*- coding: utf-8 -*-

require 'optparse'
require 'time'

# コマンドライン引数を解析してハッシュに格納する
args = {}
OptionParser.new do |parser|

  # onでTime型が指定された場合の処理
  # 文字列をTimeに変換する
  parser.accept(Time) do |s, |
    begin
      Time.parse(s) if s
    rescue
      raise OptionParser::InvalidArgument, s
    end
  end

  # オプションを指定
  # オプションが引数を取る場合は任意の文字列を設定する
  # ex.--from COPY_FROM
  # 指定しない場合、ブロックに渡される引数は
  # オプションが指定されたかどうかだけとなるためboolとなる
  parser.on('-f', '--from COPY_FROM') {|v| args[:from] = v}
  parser.on('-t', '--to COPY_TO') {|v| args[:to] = v}
  parser.on('-d', '--date DATE', Time) {|v| args[:date] = v}
  parser.parse!(ARGV)
end

p args
ruby ./use_optionparser.rb -f "~/work/from" -t "~/work/to" -d "2012/07/29"
# {:from=>"~/work/from", :to=>"~/work/to", :date=>2012-07-29 00:00:00 +0900}

32
33
4

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
32
33

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?