stdlib : file

Methods for manipulating files.
close   delete   each_line   exists?   make_dir   open   read   read_line   read_lines   rename   type   write   write_line  



Closes the file.


file.delete path

Deletes the file at the given path.


file.each_line path { line block }

Opens the file a the given path, calling the block for each line of the file.


file.each_line { line block }

Calls the block, passing in each line of the file as an argument, then closes the file.


file.exists? path

Returns true if the given path exists.


file.make_dir path

Makes a new directory at the given path.

open path path, mode path, { file | block } path, mode, { file | block }

Opens a file at the given path. If no mode is given, the default is “r” (read-only).

Possible modes:

  • “r”: read mode (the default)
  • “w”: write mode
  • “a”: append mode
  • “r+”: update mode, all previous data is preserved
  • “w+”: update mode, all previous data is erased
  • “a+”: append update mode, previous data is preserved, writing is only allowed at the end of file

If no block is given, this returns the open file handle.

If a block is given, the file handle is passed to the block. When the block is finished, the file will be closed.

read path

Read entire file into a string.



Reads a single line from the file and returns it as a string.


file.read_lines path

Reads the file into an array of lines.


file.rename original, new

Rename a file.


file.type path

Return the type of a file as a string.

Type can be

  • file
  • directory
  • link
  • socket
  • named pipe
  • char device
  • block device
  • other


file.write data

Write data to the file.


file.write_line data

Write data to the file, followed by “\n”.

Fork me on GitHub