加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用Ruby中的“文件IO模式”替换文件中的一行

发布时间:2020-12-17 04:00:04 所属栏目:百科 来源:网络整理
导读:Ruby初学者在这里! 我知道Ruby的File.open方法有某些模式,如r,w,a,r,a和免费的b.我完全理解r,w和模式的使用.但我似乎无法理解如何使用带有’符号的那些.任何人都可以提供一些链接,其中有例子和解释使用它吗? 是否可以用它来读取一行并用相同数量的内容编辑
Ruby初学者在这里!

我知道Ruby的File.open方法有某些模式,如r,w,a,r,a和免费的b.我完全理解r,w和模式的使用.但我似乎无法理解如何使用带有’符号的那些.任何人都可以提供一些链接,其中有例子和解释使用它吗?

是否可以用它来读取一行并用相同数量的内容编辑/替换它?如果是这样,那怎么样?

示例数据文件:a.txt

aaa
bbb
ccc
ddd

Demo.rb

file = File.open "a.txt","r+"
file.each do |line|
  line = line.chomp
  if(line=="bbb")then
  file.puts "big"
  end
end
file.close

我试图将“bbb”替换为“big”,但我得到的是: –
在记事本中

aaa
bbb
big

ddd

在记事本中

aaa
bbb
bigddd

解决方法

从另一个答案中抢走了这个文档,所以不是我的,解决方案就是我的

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") }

编辑2:我现在意识到这仍然可以缩短

File.write(f = "a.txt",File.read(f).gsub(/bbb/,"big"))

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读