這是一個起點:
dirs = %w(Downloads)
Hash[ dirs.map{ |dir| [dir, Dir.glob("#{dir}/*")] } ]
這是結果:
{"Downloads"=> ["Downloads/jquery-ui-1.9.1.custom.zip", ... ] }
可以細化代碼F.E.使其遞歸,從數組結果中刪除的文件夾名字......這是遞歸實現的例子:
class Dir
def self.ls_r(dir)
Hash[ dir,
entries(dir).reject{ |entry| %w(. ..).include?(entry) }.map do |entry|
entry_with_dir = File.join(dir, entry)
File.directory?(entry_with_dir) ? ls_r(entry_with_dir) : entry
end ]
end
end
puts Dir.ls_r('~/Downloads').inspect
#=> { "Downloads" => ["file1", {"Downloads/folder1"=>["subfile1"], ... ] } ... }
請注意,這不是最好的實現,因爲遞歸不考慮採取的兒童文件夾鍵應該是相對於各自的父鍵;要解決此問題,應通過遞歸來保留此信息:
class Dir
def self.ls_r(dir, key_as_last_path_component = false)
Hash[ (key_as_last_path_component ? File.split(dir).last : dir),
entries(dir).reject{ |entry| %w(. ..).include?(entry) }.map do |entry|
entry_with_dir = File.join(dir, entry)
File.directory?(entry_with_dir) ? ls_r(entry_with_dir, true) : entry
end ]
end
end
puts Dir.ls_r('~/Downloads').inspect
#=> { "Downloads" => ["file1", {"folder1"=>["subfile1"], ... ] } ... }
現在子文件夾與其父鍵相關。
你可能想看看[二叉樹](http://en.wikipedia.org/wiki/Binary_tree)。這[問題](http://stackoverflow.com/questions/12205180/implementing-binary-tree-in-ruby)可能是一個開始。 – Eric