As you might expect, you can create a new file object using
File.new
.
aFile = File.new("testfile", "r")
# ... process the file
aFile.close
|
You can create a
File
object that is open for reading, writing, or
both, according to the mode string (here we opened ``
testfile
'' for
reading with an ``
r
''). The full list of allowed modes appears
on page 326. You can also optionally specify file
permissions when creating a file; see the description of
File.new
on page 303 for details. After opening
the file, we can work with it, writing and/or reading data as needed.
Finally, as responsible software citizens, we close the file, ensuring
that all buffered data is written and that all related resources are
freed.
But here Ruby can make life a little bit easier for you. The method
File.open
also opens a file. In regular use, it behaves just
like
File.new
.
However, if there's a block associated with the
call,
open
behaves differently. Instead of returning a new
File
object, it invokes the block, passing the
newly opened
File
as a parameter. When the block exits, the file
is automatically closed.
File.open("testfile", "r") do |aFile|
# ... process the file
end
|