How to Write to Temporary File in Ruby

The Ruby programming language is an object-oriented with a large built-in library of general purpose functions. You can use these functions to accomplish many programming tasks. For example, you can write to a temporary file using the "Tempfile" class. Temporary files are useful for storing data that isn't needed after the program closes. By storing data in a temporary file, you can free up space in random access memory, which will cause your program to have less of an impact on the rest of the system.

Things You'll Need

  • Ruby programming language installed
Show More

Instructions

    • 1

      Launch the interactive Ruby console, which comes bundled with the Ruby language, by clicking on the program labeled "IRB" from your installed programs list. You can enter statements directly into the interactive console and they will be executed as soon as you hit the "Enter" key.

    • 2

      Include the Tempfile class by writing the following statement and hitting enter:

      require 'tempfile'

    • 3

      Create a temporary file using the "Tempfile.new()" constructor. The interactive console will output the path where this temporary file is stored when you press enter. You can name the temporary file by placing some text within the parenthesis in the statement. For example, to create a temporary file named "tmp" and store it in a variable named "t," you can write the following line in the interactive console:

      t = Tempfile.new('tmp')

    • 4

      Write some text to the temporary file using the "<<" operator, like this:

      t << "Some Text"

    • 5

      Flush the buffer to ensure text is written to the file. You can do this by issuing the following statement:

      t.flush()

    • 6

      Close the file after you are done writing with the following:

      t.close()

    • 7

      Exit the interactive Ruby console. The file will now be deleted from your hard drive.

Related Searches:

References

Resources

Comments

You May Also Like

Related Ads

Featured