11.2 File Access: Reading and Writing
To access files, the built-in Ruby File
class is used. This class contains multiple
methods. We use the following: open
,
close
, gets
, and puts
. The method File.open
instantiates a new object that enables
Ruby to read from or write to an existing or new file. The object returned
by File.open
can then be used by Ruby
to access the file. The following code shows how to open a file:
myfile
=
File
.
open
(
file_name
,
access_mode
)
The myfile
variable is a File
object that can now be used to interact
with the file’s contents, depending on what access mode is used. Note that
file name
and access mode
are strings. The variable file_name
is a representation of a path to a
file, such as /home/ruby/file.txt. The myfile
variable in our program is local to only
our program. Two of the most basic access modes and what they do are shown
in Table 11-1.
Mode |
Description |
|
Read access only. Points to start of the file. This is the default, but it is good programming style to specify it anyway. |
|
Write access only. Points to the beginning of the file that will overwrite the file’s content if it already exists. |
Gem of Wisdom
Files provide access to data resident in the computer system’s long-term memory. Storage in long-term memory, such as disks, provides data resiliency, namely, permanence. That is, disks work even without power, so they store things far longer than the internal random access memory, which works only if the ...
Get Computer Science Programming Basics in Ruby 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.