在 Ruby 中寫入檔案
Nurudeen Ibrahim
2022年5月18日
Ruby
Ruby File

Ruby 中的 File
類有一個用於寫入檔案的 write()
方法。該方法返回寫入的長度並確保檔案自動關閉。它具有以下語法。
File.write('/your/file/path', 'Message content')
讓我們將一條簡單的訊息寫入檔案。
File.write('my-file.txt', 'A simlpe message.')
上面的程式碼幫助我們建立一個名為 my-file.txt
的檔案(如果它尚不存在),並允許我們編寫 A simlpe message.
到檔案。如果檔案已經存在,程式碼將覆蓋檔案及其內容。
Ruby 沒有覆蓋檔案內容,而是提供了一種通過指定 mode
選項附加到內容的方法,示例如下所示。
File.write("my-file.txt", " Another simple message\n", mode: 'a')
上例中的 \n
是一個換行符,這意味著我們將寫入此檔案的以下訊息應該轉到下一行。讓我們寫另一條訊息來確認這一點。
File.write("my-file.txt", "This message should go on the next line", mode: 'a')
作為總結上述解釋的一種方式,讓我們編寫一個簡單的程式,將五行文字寫入檔案。
todos = [
"wake up, shower, and leave for work",
"Pick up John from school",
"Meet with team to practice presentation",
"Dinner with friends",
"Relax and bedtime."
]
todos.each_with_index do |todo, index|
File.write("todo-list.txt", "#{index + 1}. #{todo}\n", mode: 'a')
end
下面是執行程式後的 todo-list.txt
檔案內容。
輸出:
1. wake up, shower, and leave for work
2. Pick up John from school
3. Meet with team to practice presentation
4. Dinner with friends
5. Relax and bedtime.
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe