ファイル検索

指定フォルダ以下のフォルダ/ファイルを列挙する

lesson001.rb


Dir.open(ARGV[0]) do |dir|
dir.each do |name|
puts name
end
end
実行結果

C:\>ruby c:\study\ruby\chapter005\lesson001.rb c:\study\ruby
.
..
chapter001
chapter002
chapter003
chapter004
chapter005

ちょいと変更

lesson002.rb


def putsDir(path)
Dir.open(path) do |dir|
dir.each do |name|
puts name
end
end
end

putsDir(ARGV[0])

実行結果

C:\>ruby c:\study\ruby\chapter005\lesson002.rb c:\study\ruby
.
..
chapter001
chapter002
chapter003
chapter004
chapter005

サブフォルダも検索

lesson003.rb


def putsDir(path)
if FileTest.directory?(path)
Dir.open(path) do |dir|
dir.each do |name|
next if name == "." # 自分
next if name == ".." # 親

putsDir path + "/" + name
end
end
else
puts path
end
end

putsDir(ARGV[0])

実行結果

C:\>ruby c:\study\ruby\chapter005\lesson003.rb c:\study\ruby
c:\study\ruby/chapter001/lesson001.rb
c:\study\ruby/chapter001/lesson002.rb
c:\study\ruby/chapter001/lesson003.rb
c:\study\ruby/chapter001/lesson004.rb
c:\study\ruby/chapter001/lesson005.rb
c:\study\ruby/chapter001/lesson006.rb
c:\study\ruby/chapter001/lesson007.rb
c:\study\ruby/chapter001/lesson008.rb
c:\study\ruby/chapter001/lesson009.rb
c:\study\ruby/chapter001/lesson010.rb
c:\study\ruby/chapter001/lesson011.rb
c:\study\ruby/chapter001/ruby.bat
c:\study\ruby/chapter001/test.txt
c:\study\ruby/chapter002/lesson001.rb
c:\study\ruby/chapter002/lesson002.rb
c:\study\ruby/chapter002/lesson003.rb
c:\study\ruby/chapter002/lesson004.rb
c:\study\ruby/chapter002/lesson005.rb
c:\study\ruby/chapter002/ruby.bat
c:\study\ruby/chapter003/lesson001.rb
c:\study\ruby/chapter003/lesson002.rb
c:\study\ruby/chapter003/lesson003.rb
c:\study\ruby/chapter003/lesson004.rb
c:\study\ruby/chapter003/lesson005.rb
c:\study\ruby/chapter003/lesson006.rb
c:\study\ruby/chapter003/ruby.bat
c:\study\ruby/chapter004/lesson001.rb
c:\study\ruby/chapter004/lesson004.rb
c:\study\ruby/chapter004/lesson006.rb
c:\study\ruby/chapter004/lesson007.rb
c:\study\ruby/chapter004/lesson008.rb
c:\study\ruby/chapter004/lesson009.rb
c:\study\ruby/chapter004/lesson010.rb
c:\study\ruby/chapter004/lesson011.rb
c:\study\ruby/chapter004/ruby.bat
c:\study\ruby/chapter004/test.txt
c:\study\ruby/chapter005/lesson001.rb
c:\study\ruby/chapter005/lesson002.rb
c:\study\ruby/chapter005/lesson003.rb
c:\study\ruby/chapter005/ruby.bat