View Single Post
  #4 (permalink)  
Old 03-29-2008, 12:19 AM
bluesky bluesky is offline
D-Web Analyst
 
Join Date: Jun 2007
Posts: 201
bluesky is on a distinguished road
Default Re: Ruby File handling

Reading/writing to files

The gets method


File.open("myfile") do |file|
while content = file.gets
# ... operations on file
end
end

This code reads from the file as long as there is "something" in the file, note the "while content = file.gets" line.

The each_byte method

To be used when you need to process each character in an expression.Here's a sample:

"Sample code".each_byte {|b| puts b.chr}
Obviously, it can be used on files also, to read characters and process sequentially.

File.open("myfile") do |file|
file.each_byte {....}
end

The each_line method


Similar to each_byte, read one line at a time.
Reply With Quote