Ruby I/O

From Wiki
Revision as of 00:14, 2 February 2011 by Scott (talk | contribs) (Parsing a File)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

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')