DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Use A Regular Expression Substitution On The Contents Of A File
The following code can be used to replace content inside a file. Be warned however, that it loads the contents of the file into memory.
I chose this solution because i didn't want to use a temporary file.
def replace_in_file(filename, s, r)
lines = []
File.open(filename, "r"){|f| lines = f.readlines }
lines = lines.inject([]){|l, line| l << line.gsub(s, r)}
File.open(filename, "w"){|f| f.write(lines) }
end





