我認爲,@ ShaneQful的反應是良好的,因爲它使用你的代碼,但你可以爲他說讓這個更容易與
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))
它打開file_name
讀出它轉換成字符串這樣做是什麼。用new_color
替換(#gsub
)old_color
的所有實例,然後將其寫回file_name
。
簡單,簡單,乾淨,簡潔。
更新
標杆的
File#read
,File.open(file_name,&:read)
和File.open with block read into a string and then written back to file_name
(如ShaneQful的例子)
這是基準對傑克·倫敦的白牙包含〜75000個字與字的645個實例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%
看起來好像是File#read
和File.open(file_name,&:read)
貿易雙方在實施速度方面來來往往,但利用真正的區塊來處理同樣的操作對於這種類型的東西總是要慢得多。
這個簡單的程序使用簡介read
或#open(file_name,&:read)
(Symbol#to_proc
)。如果您需要執行可能需要多行或條件選項的詳細更改,那麼我會使用一個塊
嘗試'puts line.sub(oldcolor,newcolor)' – 2014-09-02 18:12:13
這工作! 。現在我正試圖在同一個文件中保存更改 – 2014-09-02 18:13:50
您不能原地更改文件。相反,您必須將其從磁盤讀取到內存中,進行更改並將其寫回。 – Stefan 2014-09-02 18:31:56