ディレクトリのファイルリスト

ディレクトリのファイルリストは,以下で取得できる.

Dir.chdir("./wiki")
fileList =Dir.glob("*.txt")
for i in 0..(fileList.size-1)
print fileList[i], "/n"
end

これで,拡張子がtxtのファイルの一覧がfileListに代入される.

ファイルの読み込み

ファイルの末尾はeofで確認できるので,1行ずつの読み込みは,以下のように行える.
ファイルからの読み込みは,getsで行う.

while !fr.eof
str = fr.gets
print str
end

置換して書き込む

今回のプログラム全体は,こうなった.

#!/usr/bin/ruby
def eliminateChilda(fileName)
readFilePath = "/Users/sonson/develop/Ruby/wiki/" + fileName
writeFilePath = "/Users/sonson/develop/Ruby/wiki2/" + fileName
fr = open(readFilePath,"r")
fw = open(writeFilePath,"w")
while !fr.eof
str = fr.gets
result = str.gsub(/~?n/,"?n")
fw.print result
end
fr.close
fw.close
end
def main()
Dir.chdir("./wiki")
fileList =Dir.glob("*.txt")
for i in 0..(fileList.size-1)
eliminateChilda(fileList[i])
end
end
main()