Ruby I/O: Difference between revisions

From Wiki
Jump to navigation Jump to search
 
Line 41: Line 41:
more here:
more here:
http://www.ruby-doc.org/core/classes/File.html
http://www.ruby-doc.org/core/classes/File.html
== Command-line arguments ==
<code>ARGV[0]</code> is the first of the command-line parameters, numbering naturally from zero; it is not the file or script name preceding the parameters, like <code>argv[0]</code> in C.

Latest revision as of 20:37, 5 October 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')


File Attributes

File.exists?('/some/directory/path')
File.size('/some/directory/path')

more here: http://www.ruby-doc.org/core/classes/File.html


Command-line arguments

ARGV[0] is the first of the command-line parameters, numbering naturally from zero; it is not the file or script name preceding the parameters, like argv[0] in C.