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.

4 Responses to “Occasionally I Feel Stupid”

  1. Yan Says:

    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

  2. Chris Says:

    Also also, open('file.txt').read

  3. Chas Says:

    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

  4. raul parolari Says:

    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

Leave a Reply


(textile enabled)