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.
June 20th, 2007 at 6:13 am
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.
June 25th, 2007 at 2:33 am
Good info man, Appreciated.
December 5th, 2007 at 3:40 am
this tip was really helpful. thanks!
December 18th, 2007 at 11:56 pm
Thanks dude
March 22nd, 2008 at 1:03 pm
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
April 14th, 2008 at 12:40 pm
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.
February 15th, 2009 at 4:57 am
You can also do the even simpler:
file_data = File.read(my_file)
Hooray for Ruby!