Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | CLI | Delight Casual Users | Default Values for the App's Arguments

概要

書籍 Build Awesome Command-Line Applications in Ruby2

Delight Casual Users

詳細

多くのコマンドラインは引数としてファイルリストや標準入力を使用します。
その際に、入力があれば引数から値を取得。
入力がなければ標準入力から値を取得するようにデフォルトの動作を設定します。

例としてARGV+STDINを利用した例と、
ARGFを利用した例を記します。

サンプル仕様 その1

引数で指定した入力を出力します。
引数が省略された場合は、標準入力で入力を促します。

サンプルコード その1

msg = 'please input some lines of texts. if you want to quit, input "exit".'
if ARGV.empty?
  puts msg
  STDOUT.flush
  while line = STDIN.gets
    break if line.chomp == 'exit'
    puts line
    puts msg
    STDOUT.flush
  end
else
  puts ARGV
end

出力 その1

$ ruby 1.rb
please input some lines of texts. if you want to quit, input "exit".
hoge
hoge
please input some lines of texts. if you want to quit, input "exit".
hige
hige
please input some lines of texts. if you want to quit, input "exit".
hage
hage
please input some lines of texts. if you want to quit, input "exit".
exit
$ ruby 1.rb hoge hige hage
hoge
hige
hage

サンプル仕様 その2

引数で指定したファイルを出力します。

サンプルコード その2

puts ARGF.read

サンプルテキスト1(text1.txt)

text1_1
text1_2
text1_3

サンプルテキスト2(text2.txt)

text2_1
text2_2
text2_3

出力 その2

$ ruby 2.rb text1.txt text2.txt
text1_1
text1_2
text1_3
text2_1
text2_2
text2_3

$ ruby 2.rb
hoge
hige
hage
# (Ctrl+Dを押す)
hoge
hige
hage