Quick Ruby File Operations

I was working on a quick program to read and write data to files in Ruby. I am new to Ruby so here is a quick lesson in basic Ruby file operations.

Reading Files

Writing Files

This is a pretty straight forward example. I make use of the “r” and “w” I/O modes. You can find out more about the I/O modes at the Ruby API site.

6 Responses to “Quick Ruby File Operations”

  1. Sandro Says:

    Often this small tips are exactly what a develepor is in search for. This is my case and what I found here completely answer my needs. Thanks.

  2. MHM Reddy Says:

    Good info man, Appreciated.

  3. Devi Says:

    this tip was really helpful. thanks!

  4. Rajesh Says:

    Thanks dude

  5. Jesper de Jong Says:

    It’s even better if you pass a block to File.open, like I show below. The advantage of this is that you do not need to close the file explicitly - File.open will open the file, execute the code in the block, and then automatically close the file - even when an exception occurs. So it’s more convenient and more safe, because you won’t have a resource leak in case an exception occurs:

    File.open(my_file, ‘r’) do |f|
    file_data = f.read
    end

  6. Brian Real Says:

    Okay sounds good. I tried this creating an .htm document. I was wondering if there is a page to read & write my .htm document and then have browser automatically read and execute the file I wrote. Basically have the browser open the file that my program just wrote.

Leave a Reply