我从另一个答案中获取了这个文档,所以不是我的,但解决方案是我的
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.
编辑:这里是针对您示例的解决方案。大多数情况下,整个字符串会被替换并写回文件,但是也有可能进行'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") }
编辑2:我现在意识到这还可以更短
File.write(f = "a.txt", File.read(f).gsub(/bbb/,"big"))
r+
模式打开文件,然后进行读写操作。请查看文档,它非常全面。 - Sergio Tulentsev