From: ARIMA Yasuhiro Date: 1998-10-19T10:16:18+09:00 Subject: [ruby-list:10172] Re: syntax of compare strings Regard to "[ruby-list:10165] syntax of compare strings" 有馬@FITECです。 >rubyでのスクリプト解析みたいなことをやったことがある方は >いらっしゃいませんか? Windows の Ini ファイルの形式のデータを扱うために、以下のようなものを 書きました。読み込んだデータは Hash に貯えていきます。 元ネタは、Windows 用の処理系である Delphi の TInifile クラスです。 inifile = IniFile.open("a.ini") と書くための、open の定義の仕方がよくわからないので不細工ですが、 参考になりますでしょうか? # # inifile.rb # # def new # def read(section, key) # def write(section, key, value) # def deleteKey(section, key) # def deleteSection(section) # def loadfromfile(filename = @inifilename) # def savetofile(filename = @inifilename) # def clear # class IniFile def initialize # @inifilename = filename) @sections = [] @keys = {} @values = {} end def read(section, key) @values[section+"="+key] end def write(section, key, value) @sections |= [section] @keys[section] = [] if @keys[section] == nil @keys[section] |= [key] @values[section+"="+key] = value end def deleteKey(section, key) write section, key, nil @keys[section] -= [key] end def deleteSection(section) @keys[section].each do |key| deleteKey section, key end @sections -= [section] end def loadfromfile(filename = @inifilename) return nil if not File.exist?(filename) f = File.open(filename, "r") begin while s = f.gets do s.chop!.strip! next if s == "" next if s =~ /^;.*/ if s =~ /\[([^]]+)\]/ then section = $1 next end if s =~ /([^=]+)=(.*)/ then key = $1 value = $2 write section, key, value end end ensure f.close end end def savetofile(filename = @inifilename) f = File.open(filename, "w") begin @sections.each do |section| f.printf "[%s]\n\n", section @keys[section].each do |key| value = read(section, key) f.printf "%s=%s\n", key, value end f.printf "\n\n", section end ensure f.close end end def clear @sections = [] @keys = {} @values = {} end end def test inifile = IniFile.new inifile.loadfromfile "a.ini" print "----\n" #inifile.savetofile "b.ini" inifile.savetofile "conout$" print "----\n" inifile.deleteKey "a", "a1" inifile.savetofile "conout$" print "----\n" inifile.deleteSection "b" inifile.savetofile "conout$" print "----\n" inifile.write "About", "Copyright", "Anonymouse" inifile.savetofile "conout$" end -- 有馬 康弘