I'm new to ruby and was hoping someone could help me figure out how to open a file, then using gsub to find and replace by multiple conditions.
Here's what I got so far but this doesn't seem to work as the 2nd replace var overrides the first:
text = File.read(filepath)
replace = text.gsub(/aaa/, "Replaced aaa with 111")
replace = text.gsub(/bbb/, "Replace bbb with 222")
File.open(filepath, "w") {|file| file.puts replace}
I might be tempted to write it like this...
Another nice extension to @steveRoss's answer above, using variables:
These are not string literals but variables
You're replacing from the original "text" each time, the second line needs to replace the replace:
An interesting wrinkle to this is if you don't want to rescan the data, use the block form of gsub:
This may not be the most efficient way to do things, but it's a different way to look at the problem. Worth benchmarking both ways if performance matters to you.
Change the third line to
Here is a one liner
IO.write
truncates the given file by default, so if you read the text first, perform the regexString.gsub
and return the resulting string usingFile.open
in block mode, it will replace the file's content. Nifty right?It works just as well multi-line: