Files

You can manipulate file directories (folders) and files from within Ruby programs using methods from the Dir and File classes. For documentation, see http://www.ruby-doc.org/core/classes/Dir.html and http://www.ruby-doc.org/core/classes/File.html. For example, you can change directories (using an absolute path), and then store the value of the directory path in a variable as follows:

Dir.chdir( "/Users/penelope" )
home = Dir.pwd # => "/Users/penelope/"
p home # => "/Users/penelope"

If you need a directory, create it with mkdir; later on, delete it with rmdir (or delete, a synonym of rmdir):

Dir.mkdir( "/Users/herman/sandbox" )
Dir.rmdir( "/Users/herman/sandbox" )

You can also set permissions (where the mask 755 sets permissions owner, group, world [anyone] to rwxr-xr-x where r = read, w = write, and x = execute) on a new directory (not one that already exists) with mkdir:

Dir.mkdir( "/Users/floyd/sandbox", 755 )

Creating a New File

To create a new file and open it at the same time, use the File method new, like this:

file = File.new( "file.rb", "w" )

The first argument names the new file, and the second argument specifies the file mode, either r for readable, w for writable, or x for executable. The effects of the different modes are shown in Table 6.

Table 6. File modes

Mode

Description

"r"

Read-only, starts at beginning of file (default mode).

"r+"

Read-write, starts at beginning of file.

"w"

Write-only, truncates existing file to zero length or creates a new file for writing.

"w+"

Read-write, ...

Get Ruby Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.