hakeの日記

Windows環境でプログラミングの勉強をしています。

Rubyで書いてみる

せっかくRuby本を買ったので、昨日のシェルスクリプトRubyで書いてみました。一から書いたという意味で初Rubyです(笑)
単純なプログラムではありますけれども、意外と簡単に書き換えができました。シェルスクリプトと比べて、正規表現は使いやすいですね、でもファイルの入出力の手続きが面倒くさいなぁ。あとエラーが結構親切なのにはオドロキました。


#!/usr/bin/env ruby
#
#   eb2iq.rb
#   Convert EBt outputfile(euc) to IQNotes inputfile(WZ format)
#

#p ARGV[0]
#p ARGV[1]


if ARGV[1] == nil then
   print "Usage: eb2iq.rb  EBt_outputfile(euc_JP)  WZ_file\n"
   exit
end

INFILE = ARGV[0]
OUTFILE = "temp1.tmp"

begin
   infile = open( INFILE )
rescue
   print "EBt_outputfile can not open\n"
   exit
end

begin
   outfile = open( OUTFILE , "a")
rescue
   print "tempolary file can not open\n"
   exit
end


period = ""
flag = ""

while line = infile.gets

   if /^-+$/ =~ line  then
      # skip separate line
   elsif /^title:(.+)/ =~ line  then   # title
      period = period + "."
      title  = $1
      flag   = "1"
   else
      if flag == "1" then
         outfile.print( period , title , "\n")
         flag = ""
      end
      outfile.print( line )
      period = ""
   end
end

infile.close
outfile.close

system("nkf -s -Lw #{OUTFILE} > #{ARGV[1]}")
system("rm #{OUTFILE}")