[temp] Pages 120-1: Opening and closing files, Reading and writing files
Listen to this article.
Value: Medium
Level: Easy
Summary:
You can create a File object and read from it, write to it, or both. You can do it using File#new() or File#open(): the only difference between the two is that the latter can be associated with a block. If you use File#open() with an associated block Ruby will pass the file as a parameter to the block, and at the end will close the file. In case of exception Ruby will nevertheless close the file before raising it: if there's no block associated, or if you're using File#new(), you'll have to ensure to close the file as Ruby won't do it automatically.
Memo: Be sure your file will be closed even if an exception is raised.
Example:
Assuming we have data in data.txt we can read it in a standard way...
print File.new("data.txt", "r").readlines
# produces the same otuput of...
print File.open("data.txt", "r").readlines
... or in a "safe" way
File.open("data.txt", "r") do |a|
print a.readlines
end
# produces the same output of...
File.open("data.txt", "r") do |b|
while line = b.gets
print line
end
Finally we could have show.rb...
while line = gets
puts line
end
...and simply pass it one or more filenames in the command line
% ruby show.rb data.txt
Doubts: 0
Reported errata (at 10/17/06 14:17:18 PDT): 0
Errata I found: 1
My suggestions to the author: 0
Level: Easy
Summary:
You can create a File object and read from it, write to it, or both. You can do it using File#new() or File#open(): the only difference between the two is that the latter can be associated with a block. If you use File#open() with an associated block Ruby will pass the file as a parameter to the block, and at the end will close the file. In case of exception Ruby will nevertheless close the file before raising it: if there's no block associated, or if you're using File#new(), you'll have to ensure to close the file as Ruby won't do it automatically.
Memo: Be sure your file will be closed even if an exception is raised.
Example:
Assuming we have data in data.txt we can read it in a standard way...
print File.new("data.txt", "r").readlines
# produces the same otuput of...
print File.open("data.txt", "r").readlines
... or in a "safe" way
File.open("data.txt", "r") do |a|
print a.readlines
end
# produces the same output of...
File.open("data.txt", "r") do |b|
while line = b.gets
print line
end
Finally we could have show.rb...
while line = gets
puts line
end
...and simply pass it one or more filenames in the command line
% ruby show.rb data.txt
Doubts: 0
Reported errata (at 10/17/06 14:17:18 PDT): 0
Errata I found: 1
- Typo on page 121: "w" instead of "we".
My suggestions to the author: 0
0 Comments:
Post a Comment
<< Home