Rubyにはコマンドラインを扱う方法が色々ありますが、今回はコマンドライン引数を扱うための有名なライブラリとして、optparseを紹介します。
概要
optparseは、Rubyの標準ライブラリであり、コマンドラインオプションを解析するためのライブラリです。
これにより、Rubyのスクリプトを実行する際に、ユーザーが指定するオプションを解析し、適切な値を取得することができます。
下記、公式のマニュアルがあるので参照ください。
library optparse (Ruby 3.1 リファレンスマニュアル)
基本的な使い方
1) まずは、optparseを使うために、requireします。
sample
require 'optparse'
2) 次に、OptionParserオブジェクトを作成します。
sample
options = OptionParser.new do |opt|
# オプションを追加する
end
3) opt.onを使って、コマンドライン引数として渡されるオプションを追加します。
sample
options = OptionParser.new do |opt|
opt.on("-m M", "--month=M", Integer, "Display the calendar of month M") do |m|
# オプションに応じた処理を書く
end
4) opt.parse!(ARGV)を使って、実際に引数を解析します。
sample
options.parse!(ARGV)
このような形式で、optparseを使ってコマンドライン引数を解析することができます。
具体例
実際に、私がカレンダーアプリで作成したプログラムを共有いたします。
コマンドライン引数として、「-m ○」と指定すると、○月のカレンダーが表示される仕様です。
最後に完成したコードを共有します。
下記のような感じです。
terminal
# オプションなしで実行すると、実行した日の月カレンダーを表示。
$ ruby calendar.rb
February 2023
Su Mo Tu We Th Fr Sa
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28
terminal
# コマンドライン引数(-m)で、7月分のカレンダーを指定する。
$ ruby calendar.rb -m 7
July 2023
Su Mo Tu We Th Fr Sa
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
terminal
# コマンドライン引数(--month)で、7月分のカレンダーを指定する。
$ ruby calendar.rb --month 11
November 2023
Su Mo Tu We Th Fr Sa
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30
terminal
# コマンドライン引数(-m)で、あり得ない引数(13月は存在しない)を指定する。
$ ruby calendar.rb -m 13
13 is neither a month number (1..12) nor a name
こんな感じで、コマンドライン引数を設定して、Rubyを実行することができます。
完成品
よかったら参考にしてみてください!
sample
# frozen_string_literal: true
require 'date'
require 'optparse'
def display_calendar(year, month)
date = Date.new(year, month, 1)
last_day = date.next_month.prev_day.day
month_name = date.strftime('%B')
# puts "--開発用-------------------------"
# puts date
# puts last_day
# puts "--開発用-------------------------"
# puts "\n\n"
puts "#{month_name} #{year}".center(20)
puts 'Su Mo Tu We Th Fr Sa'
start_day = date.wday # 日曜日から数えた日付の曜日(0 = Sunday, 1 = Monday, ..., 6 = Saturday)を取得
(0...start_day).each { print ' ' }
(1..last_day).each do |day|
print '%2d ' % day # 日曜日から数えた日付
if (start_day + day - 1) % 7 == 6 #2月の場合、3 + 3 = 6, 6%7 == 6 : true
puts "\n"
end
end
puts "\n"
end
# コマンドライン引数が、1~12月でない場合の出力
def get_calendar_for_month(year, month)
if (1..12).include?(month)
display_calendar(year, month)
return
end
puts "#{month} is neither a month number (1..12) nor a name"
end
def main
# 本日日付から取得、初期化
year = Time.now.year
month = Time.now.month
# コマンドライン引数
OptionParser.new do |opt|
## 引数の挙動を定義
opt.on('-m M', '--month M', Integer, 'Select of month M') do |m|
unless (1..12).include?(m)
puts "#{m} is neither a month number (1..12) nor a name"
exit
end
month = m
end
## 定義されたコマンドラインオプションを解析・実行
opt.parse!(ARGV)
end
display_calendar(year, month)
end
main
最後に
最後までありがとうございました。
改善点があれば、ご指摘ください。いいね頂けると嬉しいです!