Ruby I/O: Difference between revisions
Jump to navigation
Jump to search
(No difference)
|
Revision as of 00:14, 2 February 2011
Parsing a File
To extract the contents of a file as a single string:
lines = open('test.txt').read
To extract the contents of a file as an array of lines:
lines = open('test.txt').readlines
To process a file line-by-line:
open('test.txt').each do |line|
do something with line
end
Write to a file
output = open('output.txt', 'w')
output.puts("Here is the first line")
output.puts("and here is the second line")
List a directory
list_of_files = Dir.foreach('/some/directory/path')