2011-09-18 56 views
9

我對Ruby很感興趣,我正在制定一些katas,並且卡住了這個愚蠢的問題。我需要1個文件的內容複製到一個新文件中1行代碼Ruby在一行代碼中對文件進行讀取/寫入

首先嚐試:

File.open(out, 'w').write(File.open(in).read) 

不錯,但它是錯的,我需要關閉文件:

File.open(out, 'w') { |outf| outf.write(File.open(in).read) } 

然後當然關閉讀:

File.open(out, 'w') { |outf| File.open(in) { |inf| outf.write(outf.read)) } } 

這就是我想出的,但它並不像1行代碼我:(

想法?

Regards,

+2

不fileutils中,File.copy算什麼? – Calin

+0

我沒有看到任何換行符或半冒號..... –

+0

@matt我知道,但如果我必須對我自己,我將不得不在一些行中斷 – Calin

回答

14

有很多方法。你可以簡單地調用例如命令行:

`cp path1 path2` 

但我猜你正在尋找的東西,如:

File.open('foo.txt', 'w') { |f| f.write(File.read('bar.txt')) } 
+0

是的,這是我的第二選擇,但如何關於File.read('bar.txt'),是否需要關閉? – Calin

+0

它會自動爲您完成。 –

+0

你的意思是這樣的http://stackoverflow.com/questions/4795447/rubys-file-open-and-the-need-for-f-close – Calin

2

你可以做到以下幾點:

File.open(out_file, "w") {|f| f.write IO.read(in_file)} 
1

你可以試試:

IO.binwrite('to-filename', IO.binread('from-filename')) 

檢查紅寶石文檔:

IO::binwrite & IO::binread

相關問題