April 25, 2007

Posted by John

Older: Don't Take Sides

Newer: RailsConf 2007

Occasionally I Feel Stupid

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 Comments

  1. 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. Also also, open('file.txt').read

  3. 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. 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

Sorry, comments are closed for this article to ease the burden of pruning spam.

About

Authored by John Nunemaker (Noo-neh-maker), a programmer who has fallen deeply in love with Ruby. Learn More.

Projects

Flipper
Release your software more often with fewer problems.
Flip your features.