Title here
Summary here
Our first program will demonstrate how to work with temporary files and directories. Here’s the full source code:
require 'tempfile'
require 'fileutils'
def check(error)
raise error if error
end
# The easiest way to create a temporary file is by using
# Tempfile.new. It creates a file and opens it for reading and writing.
f = Tempfile.new('sample')
puts "Temp file name: #{f.path}"
# Clean up the file after we're done. Ruby will automatically
# delete temporary files, but it's good practice to do this explicitly.
f.close
f.unlink
# We can write some data to the file.
f = Tempfile.new('sample')
f.write([1, 2, 3, 4].pack('C*'))
f.close
# If we intend to work with many temporary files, we may
# prefer to create a temporary directory.
# Dir.mktmpdir creates a temporary directory and returns its path.
Dir.mktmpdir('sampledir') do |dir|
puts "Temp dir name: #{dir}"
# Now we can create files in our temporary directory.
file_path = File.join(dir, 'file1')
File.write(file_path, [1, 2].pack('C*'))
endTo run the program:
$ ruby temporary_files_and_directories.rb
Temp file name: /tmp/sample20230615-12345-abcdef
Temp dir name: /tmp/sampledir20230615-12345-ghijklIn this Ruby version:
Tempfile class to create temporary files.Dir.mktmpdir method is used to create a temporary directory.File.join to create file paths, similar to the original filepath.Join.pack('C*') to convert an array of integers to a binary string.This script demonstrates how to work with temporary files and directories in Ruby, which is useful for creating data that isn’t needed after the program exits.
Comments powered by Disqus