- Read Tutorial
- Watch Guide Video
In this lesson we are going to learn something that is very practical: how to append information to the end of a file. We're going to 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 in Ruby
10.times 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 are create or open a file called server_logs.txt
in append mode. In this file we are appending the time when our server started. We are running it through a loop with f
being the block variable. We are doing it ten times with a one second break between each iteration.
devCamp 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 number of seconds the process should pause as the argument.
When you run this file, your output should have the message Record saved
written 10
times.
Record saved... Record saved... Record saved... Record saved... Record saved... Record saved... Record saved... Record saved... Record saved... Record saved...
Now, if you open the file called server_logs.txt
, you get to see the timestamp, with a one second break.
Server started at: 2016-09-05 17:49:18 -0500 Server started at: 2016-09-05 17:49:19 -0500 Server started at: 2016-09-05 17:49:20 -0500 Server started at: 2016-09-05 17:49:21 -0500 Server started at: 2016-09-05 17:49:22 -0500 Server started at: 2016-09-05 17:49:23 -0500 Server started at: 2016-09-05 17:49:24 -0500 Server started at: 2016-09-05 17:49:25 -0500 Server started at: 2016-09-05 17:49:26 -0500 Server started at: 2016-09-05 17:49:27 -0500
Let's run this file one more time to see if values are getting appended to our file. If you open the server_logs.txt
file, you should see 20
records because we've run the code twice.
So, this is a component that you can build in a real-life application.