式を指定したファイルを読み込んで、計算結果を付加するスクリプトです。「eval」関数を利用することによって、文字列で指定した内容を計算し、結果を返します。
# calc.rb
# 内容 : 電卓プログラム
# 入力ファイルに式をセットしておくと出力ファイルに式=値という形式で出力される。
# (例)入力ファイル 出力ファイル
# 15 + 22 15 + 22 = 37
# 41 - 29 41 - 29 = 12
# 12 * 15 12 * 15 = 180
# 128 / 8 128 / 8 = 16
# Copyright (c) 2002-2015 Mitsuo Minagawa, All rights reserved.
# (minagawa@fb3.so-net.ne.jp)
# 使用方法 : c:\>ruby calc.rb
#
# 入力ファイル
in1_file = open("input.txt","r")
# 出力ファイル
out1_file = open("output.txt","w")
# 主処理
while (line1 = in1_file.gets)
line1.chomp!
out1_file.print "#{line1} = ",eval(line1),"\n"
end
# ファイルのクローズ
in1_file.close
out1_file.close
15 + 22 41 - 29 12 * 15 128 / 8
15 + 22 = 37 41 - 29 = 12 12 * 15 = 180 128 / 8 = 16