このドキュメントを別の回答から奪ったので、私のものではなく、解決策は私のものです
r Read-only mode. The file pointer is placed at the beginning of the file. This is the default mode.
r+ Read-write mode. The file pointer will be at the beginning of the file.
w Write-only mode. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
w+ Read-write mode. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
a Write-only mode. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
a+ Read and write mode. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
編集: ここでサンプルの解決策を示します。ほとんどの場合、文字列全体が gsubbed されてファイルに書き戻されますが、ファイル全体を書き換えずに「infile」を置き換えることも可能です。同じ長さの文字列に置き換えるには注意が必要です。 .
File.open('a.txt', 'r+') do |file|
file.each_line do |line|
if (line=~/bbb/)
file.seek(-line.length-3, IO::SEEK_CUR)
file.write 'big'
end
end
end
=>
aaa
big
ccc
ddd
そして、これはより従来の方法ですが、他のほとんどのソリューションよりも簡潔です
File.open(filename = "a.txt", "r+") { |file| file << File.read(filename).gsub(/bbb/,"big") }
EDIT2:これはさらに短くできることに気づきました
File.write(f = "a.txt", File.read(f).gsub(/bbb/,"big"))