Appending a file
In this section, you will learn something that is very practical: how to append information to the end of a file. We'll take the case study of creating a log file that we add data to at various intervals. This is a common feature that you'll need to build in a real-world Ruby project, so this is an important skill to learn.
Building a log file
The following is a simple example code for building a log file:
do sleep 1 puts "Record saved..." File.open("files-lessons/server_logs.txt", "a") {|f| f.puts"Server started at: #{Time.new}"} end
In this code, we create or open a file called server_logs.txt
in the append mode. In this file, we append the time when our server started. We run it through a loop with f
being the block variable. We do it ten times with a one second break between each iteration.
Note
Whenever you want to mimic a process, or in this case, ensure that each iteration occurs at a different time, it's common to leverage the sleep
method, which takes the...