$ uname -mrsv
Linux 2.6.26-2-amd64 #1 SMP Tue Jan 25 05:59:43 UTC 2011 x86_64
$ ruby -v
ruby 1.8.7 (2008-08-11 patchlevel 72) [x86_64-linux]
$ cat ./filelist.rb
# 指定したディレクトリパスに含まれるファイルやディレクトリのリストを返す。
# ==== Args
# target_dir :: [String] ディレクトリのパス
# filelist :: [bool] ファイルを戻り値に含めるか
# dirlist :: [bool] ディレクトリを戻り値に含めるか
# ==== Return
# ファイルやディレクトリのリスト
def get_entries(target_dir, filelist, dirlist)
entries = Dir.entries(target_dir)
result = []
entries.each{|e|
if e != '.' && e != '..'
path = target_dir + '/' + e
result.push(e) if filelist && FileTest.file?(path)
result.push(e) if dirlist && FileTest.directory?(path)
end
}
return result
end
# for test
puts "{{{files}}}"
files = get_entries($*[0], true, false)
files.sort!
puts files.inspect
files.reverse!
puts files.inspect
# for test
puts "{{{dirs}}}"
dirs = get_entries($*[0], false, true)
dirs.sort!
puts dirs.inspect
dirs.reverse!
puts dirs.inspect
$ ruby ./filelist.rb /home/hoge/data
{{{files}}}
[]
[]
{{{dirs}}}
["2011"]
["2011"]
$ ruby ./filelist.rb /home/hoge/data/2011
{{{files}}}
["0308_01.txt", "0319_01.txt", "0321_01.txt", "0321_02.txt", "0321_03.txt", "0321_04.txt", "0321_05.txt", "0322_01.txt", "0322_02.txt", "0322_03.txt", "0323_01.txt", "0323_02.txt", "0323_03.txt", "0323_04.txt", "0324_01.txt", "0324_02.txt", "0325_01.txt", "0326_01.txt", "0326_02.txt", "0326_03.txt", "0326_04.txt", "0326_05.txt", "0326_06.txt", "0326_07.txt", "0326_08.txt", "0326_09.txt", "0326_10.txt", "0326_11.txt", "0326_12.txt"]
["0326_12.txt", "0326_11.txt", "0326_10.txt", "0326_09.txt", "0326_08.txt", "0326_07.txt", "0326_06.txt", "0326_05.txt", "0326_04.txt", "0326_03.txt", "0326_02.txt", "0326_01.txt", "0325_01.txt", "0324_02.txt", "0324_01.txt", "0323_04.txt", "0323_03.txt", "0323_02.txt", "0323_01.txt", "0322_03.txt", "0322_02.txt", "0322_01.txt", "0321_05.txt", "0321_04.txt", "0321_03.txt", "0321_02.txt", "0321_01.txt", "0319_01.txt", "0308_01.txt"]
{{{dirs}}}
[]
[]
tags: ruby
Posted by NI-Lab. (@nilab)