Ruby I/O: Difference between revisions
Jump to navigation
Jump to search
Line 28: | Line 28: | ||
== List a directory == | == List a directory == | ||
<source lang="ruby"> | |||
list_of_files = Dir.foreach('/some/directory/path') | |||
</source> | |||
== File Attributes == | |||
<source lang="ruby"> | <source lang="ruby"> | ||
File.exists?('/some/directory/path') | |||
File.size('/some/directory/path') | |||
</source> | </source> | ||
more here: | |||
http://www.ruby-doc.org/core/classes/File.html |
Revision as of 21:25, 13 September 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')