Jan 172010
 

Reads a file line by line into an array my_stuff

my_stuff = []
file = File.new(“config/random_categories.txt”, “r”)
while (line = file.gets)
my_stuff << line.chop!
end
file.close
my_stuff

Pass file to block

File.open(“my_file.rb”, “r”) do |infile|
while (line = infile.gets)
puts “#{counter}: #{line}”
counter = counter + 1
end
end

Read File with Exception Handling

counter = 1
begin
file = File.new(“readfile.rb”, “r”)
while (line = file.gets)
puts “#{counter}: #{line}”
counter = counter + 1
end
file.close
rescue => err
puts “Exception: #{err}”
err
end
 Posted by at 12:00 pm  Tagged with:

 Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.