I think that @ShaneQful's response is good because it uses your code but you can as he stated make this far easier with
file_name = "D:/test.txt"
old_color = "white"
new_color = "black"
File.write(file_name,File.open(file_name,&:read).gsub(old_color,new_color))
What this does is it opens file_name
reads it out into a string. Replaces (#gsub
) all the instances of old_color
with new_color
and then writes it back to file_name
.
Simple, easy, clean and concise.
Update
Benchmarking of File#read
, File.open(file_name,&:read)
, and File.open with block read into a string and then written back to file_name
(as in ShaneQful's example)
This was benchmarked against Jack London's White Fang which contains ~75,000 words and 645 instances of the word white
#Benchmark
Rehearsal --------------------------------------------------------
File#read 0.375000 0.484000 0.859000 ( 1.462000)
File.open(&:read) 0.437000 0.530000 0.967000 ( 1.480000)
File.open with block 1.404000 0.359000 1.763000 ( 2.150000)
----------------------------------------------- total: 3.589000sec
user system total real
File#read 0.452000 0.499000 0.951000 ( 1.401000)
File.open(&:read) 0.483000 0.421000 0.904000 ( 1.445000)
File.open with block 1.529000 0.328000 1.857000 ( 2.120000)
#Fruity
Running each test 2 times. Test will take about 3 minutes.
File.open(&:read) is similar to File#read
File#read is faster than File.open with block by 50.0% ± 10.0%
It seems File#read
and File.open(file_name,&:read)
trade hands back and forth as to the speed of implementation but utilizing a true block to handle the same operation is always much slower for this type of thing.
Synopsis for easy procedures like this use read
or #open(file_name,&:read)
(Symbol#to_proc
). If you need to perform elaborate changes that may take multiple lines or conditional options then I would use a block