Ruby:
Створення тимчасового файлу

How to: / Як це зробити:

Ruby provides a simple way to work with temporary files using the Tempfile class. Here’s an example:

require 'tempfile'

Tempfile.create('tempfile_example') do |tempfile|
  # Write something to the temporary file
  tempfile.write("Hello, this is a temporary message!")

  # Rewind the file before you read it, just like a cassette tape
  tempfile.rewind

  # Read from the file
  puts tempfile.read  # Output: Hello, this is a temporary message!

  # No need to delete, it's handled automatically
end

Deep Dive / Поглиблене вивчення:

The Tempfile class has been a part of Ruby’s Standard Library for ages, helping developers manage temporary files easily. An alternative is to manage files manually, creating and deleting them, which is riskier due to potential file leaks. Under the hood, Tempfile creates files in a special temp directory, which on most UNIX-like systems is ‘/tmp’. The files are usually named with a random sequence to avoid clashes, and get deleted automatically when the object is garbage collected or when the program exits.

See Also / Дивіться також: