Tbpgr Blog

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

Ruby | CLI | Play Well with Others | Format Output One Record per Line, Delimiting Fields

概要

書籍 Build Awesome Command-Line Applications in Ruby2

Play Well with Others

詳細

1レコード、デリミタ区切りのフィールドの構成にすることによって
後続のアプリケーションが加工しやすいフォーマットになります。

サンプル

引数1〜引数2の数値の加算を一桁ずつ表示するアプリケーションを作ります。
表示フォーマットは1計算1行、カンマ区切りで「計算全体」「加算元1」「加算元2」「加算結果」です。

from = ARGV.first.to_i
to = ARGV.last.to_i

(from..to).each_cons(2) do |one, other|
  sum = one + other
  puts "#{one} + #{other} = #{sum},#{one},#{other},#{sum}"
end

実行してみます

$ ruby good.rb 1 10
1 + 2 = 3,1,2,3
2 + 3 = 5,2,3,5
3 + 4 = 7,3,4,7
4 + 5 = 9,4,5,9
5 + 6 = 11,5,6,11
6 + 7 = 13,6,7,13
7 + 8 = 15,7,8,15
8 + 9 = 17,8,9,17
9 + 10 = 19,9,10,19

# cut コマンドを利用して4項目目だけを表示する
$ ruby good.rb 1 10 | cut -d ',' -f4
3
5
7
9
11
13
15
17
19

# cut コマンドを利用して4項目目だけを表示し、その結果をsortコマンドで数値順の降順表示
$ ruby good.rb 1 10 | cut -d ',' -f4 | sort -nr
19
17
15
13
11
9
7
5
3