Occasionally I Feel Stupid
April 25th, 2007
Why? Well, other than the johnisms that my friends know me for, I just discovered File.read tonight. Check out this dandy I wrote in the past:
begin
file = File.open('file.txt', 'r')
data = file.read
ensure
file.close
end
Now that I am taking the time to read through the Standard Library, I’m having all kinds of “Oh, duh” moments. The easy way to do the above maneuver is:
data = File.read('file.txt')
So what is the lesson of the day? Get to know the Standard Library. Take some time to read through the various classes and get an overview of what they do. You don’t have to know all the details but knowing that they exist is sure to save you time (and beauty) in the future.

April 26th, 2007 at 12:20 AM
Also, File like many other resources in ruby, can take a block that ensures cleanup:
File.open(“file”) do |f| #do anything you want here end
the file will automatically be closed for you
April 26th, 2007 at 02:20 AM
Also also,
open('file.txt').readApril 28th, 2007 at 01:57 PM
Ha… remember when you suggested that I learn Ruby before starting in on Rails?
That’s why this is the first place I look – and the only documentation I have linked from my bookmarks toolbar: Builtins
July 18th, 2007 at 08:52 PM
It is perhaps worth to add that these one-liners are great for a quick job; however, as they do not catch exceptions, the best (for deployment) is in a way similar to the first version that you wrote:
begin data = File.read(‘hope_is_there.txt’) rescue Exception => e puts “your file is not there: #{e}” end