This page contains automated test results for code from O'Reilly's Ruby Cookbook. If this code looks interesting or useful, you might want to buy the whole book.
| Files and Directories | ||
|---|---|---|
| Code | Expected | Actual |
open('beans.txt', "w") do |file|
file.puts('lima beans')
file.puts('pinto beans')
file.puts('human beans')
end
open('beans.txt') do |file|
file.each { |l| puts "A line from the file: #{l}" }
end |
A line from the file: lima beans A line from the file: pinto beans A line from the file: human beans A stereotypical Unix path. |
A line from the file: lima beans A line from the file: pinto beans A line from the file: human beans |
open('/etc/passwd') |
A stereotypical Windows path; note the drive letter. |
|
open('c:/windows/Documents and Settings/User1/My Documents/ruby.doc')
open('c:\\windows\\Documents and Settings\\User1\\My Documents\\ruby.doc')
$stdin.each { |l| puts l }
$stdin.each { |l| $stdout.puts l } |
create_tree.rb |
Errno::ENOENT: No such file or directory - c:/windows/Documents and Settings/User1/My Documents/ruby.doc from (irb):10:in `initialize' from (irb):10 Errno::ENOENT: No such file or directory - c:\windows\Documents and Settings\User1\My Documents\ruby.doc from (irb):11:in `initialize' from (irb):11 |
def create_tree(directories, parent=".")
directories.each_pair do |dir, files|
path = File.join(parent, dir)
Dir.mkdir path unless File.exists? path
files.each do |filename, contents|
if filename.respond_to? :each_pair # It's a subdirectory
create_tree filename, path
else # It's a file
open(File.join(path, filename), 'w') { |f| f << contents || "" }
end
end
end
end
require 'create_tree'
create_tree 'test' =>
[ 'An empty file',
['A file with contents', 'Contents of file'],
{ 'Subdirectory' => ['Empty file in subdirectory',
['File in subdirectory', 'Contents of file'] ] },
{ 'Empty subdirectory' => [] }
]
require 'find'
Find.find('test') { |f| puts f } |
test test/Empty subdirectory test/Subdirectory test/Subdirectory/File in subdirectory test/Subdirectory/Empty file in subdirectory test/A file with contents test/An empty file |
test test/Empty subdirectory test/Subdirectory test/Subdirectory/File in subdirectory test/Subdirectory/Empty file in subdirectory test/A file with contents test/An empty file |
File.read('test/Subdirectory/File in subdirectory') |
"Contents of file" | "Contents of file" |