ruby cookbook -- Files and Directories
Chapter 6. Files and Directories
ディレクトリ構造を作成するコード
Now I can present th directory structure as a data structure and you can create it with a single method call:
==============
ちょっと疑問ですが、stringもeach|key,value|できますか?試す
irb(main):019:0> 'a'.each do | t,td|
irb(main):020:1* puts 1 if t
irb(main):021:1> puts 2 if td
irb(main):022:1> end
1
=> "a"
なるほど.
ディレクトリ構造を作成するコード
# create_tree.rb
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
Now I can present th directory structure as a data structure and you can create it with a single method call:
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
File.read('test/Subdirectory/File in subdirectory')
# => "Contents of file"
==============
ちょっと疑問ですが、stringもeach|key,value|できますか?試す
irb(main):019:0> 'a'.each do | t,td|
irb(main):020:1* puts 1 if t
irb(main):021:1> puts 2 if td
irb(main):022:1> end
1
=> "a"
なるほど.