6. 大手町.rb #8 発表資料 「Rubyの Dir、File、IOについて」
Dir.chdir
いわゆる cd
ディレクトリを移動できる
do ~ end の中だけ該当のディレクトリ
抜けると元に戻る
5
Dir.chdir("/var/spool/mail")
puts Dir.pwd
Dir.chdir("/tmp") do
puts Dir.pwd
Dir.chdir("/usr") do
puts Dir.pwd
end
puts Dir.pwd
end
puts Dir.pwd
/var/spool/mail
/tmp
/usr
/tmp
/var/spool/mail
/var/spool/mail /tmp /usr /tmp /var/spool/mail
7. 大手町.rb #8 発表資料 「Rubyの Dir、File、IOについて」
Find.find
標準添付ライブラリ Find もベンリ
Find.find でそのディレクトリ以下のすべてのファイルを処理対象にできる
スキップした方がいいディレクトリについては Find.prune で抜けられる
6
require 'find'
total_size = 0
Find.find(Dir.home) do |path|
if File.directory?(path)
if File.basename(path).start_with?(".")
Find.prune # Don't look any further into this directory.
end
else
total_size += File.size(path)
end
end
13. 大手町.rb #8 発表資料 「Rubyの Dir、File、IOについて」
IO.read、IO.write
IO.read : ファイルの内容を取得できる
IO.write : ファイルに引数の内容を書き込む
12
IO.read("testfile") #=> "This is line one¥nThis is line
two¥nThis is line three¥nAnd so on...¥n"
IO.write("testfile", "0123456789") #=> 10
# File would now read: "0123456789"
14. 大手町.rb #8 発表資料 「Rubyの Dir、File、IOについて」
IO#each_line、IO#each_char ほか
IO#each_byte :1バイトごと
IO#each_char :1文字ごと
IO#each_codepoint :
コードポイントごと
IO#each_line :1行ごと
13
File.open("testfile") do |f|
f.each_line do |line|
puts "#{f.lineno}: #{line}"
end
end
File.open("testfile") do |f|
checksum = 0
f.each_byte do |byte|
checksum ^= byte
end
end
File.open("testfile") do |f|
f.each_char do |char|
print char
end
end
File.open("testfile") do |f|
f.each_codepoint.with_index do |codepoint, index|
puts "#{index}: #{[codepoint].pack("U")} #{codepoint}"
end
end