Ruby 在一个文件中搜索和替换

Ruby 在一个文件中搜索和替换,ruby,search,replace,Ruby,Search,Replace,我是Ruby新手,我正在尝试使用RegEx在输入文本文件中进行多个搜索和替换,但是我的代码不起作用,我想我理解它为什么不起作用,但我不知道我需要什么语法来让它起作用。 这是我的密码: # encoding: utf-8 #!/usr/bin/ruby # open file to read and write file = File.open("input.txt", "r+") # get the contents of the file contents = file.read file.

我是Ruby新手,我正在尝试使用RegEx在输入文本文件中进行多个搜索和替换,但是我的代码不起作用,我想我理解它为什么不起作用,但我不知道我需要什么语法来让它起作用。 这是我的密码:

# encoding: utf-8
#!/usr/bin/ruby

# open file to read and write
file = File.open("input.txt", "r+")
# get the contents of the file
contents = file.read
file.close

reassign = contents.gsub(/\w+/, '£££££')

# save it out as a new file
new_file = File.new("output.txt")
new_file.write(reassign)
new_file.close
以下是错误消息:

C:/Users/parsonsr/RubymineProjects/Test 3/test3.rb:14:in `write': not opened for writing (IOError)
    from C:/Users/parsonsr/RubymineProjects/Test 3/test3.rb:14:in `<top (required)>'
    from -e:1:in `load'
    from -e:1:in `<main>'
C:/Users/parsonsr/RubymineProjects/test3/test3.rb:14:in'write':未打开进行写入(IOError)
来自C:/Users/parsonsr/RubymineProjects/test3/test3.rb:14:in`'
from-e:1:in“load”
from-e:1:in`'
我尝试使用数组传递每一行并更改相关内容,但它只将数组中的内容保存到输出,而不保存文件的其余部分。 我需要它来更改一个文件中已有的文本,或者更改文本,然后将新更改保存到输出文件中,以最简单的方式为准。 希望这是有意义的。 谢谢

请看一下。请注意,文件#open默认接收模式“r”。 所以答案是:改变

File.new("output.txt")

在Ruby中可以做的另一件事是:

File.write("output.txt", reassign)
或:

此外,我不知道目的是什么,但是考虑一个大文件,你可能想读取一批线,并将它们每次写入输出文件,而不是同时读取所有的内存。

File.write("output.txt", reassign)
File.open("output.txt", "w")