2012-11-23 54 views
1

我想構建一個用於存儲目錄的哈希。我想要有多個級別的密鑰。在比賽中,我想要一個文件數組。它就像電腦上的目錄結構。看起來散列是做這件事的最好方法。如何通過Ruby中的數組存儲和檢索哈希

考慮到我有文件夾["folder1", "folder1a", "folder1ax"]的數組,我該怎麼辦:

  1. 設置使用的文件夾結構爲重點和文件作爲一個數組值的哈希,並
  2. 查詢的哈希使用文件夾結構?

我使用它來解析出URL以在文件夾結構中顯示它們,而且它非常類似於在Rails應用程序中轉儲到JSTree中。因此,如果您有更好的替代方法來顯示5000個適合Rails視圖的URL,請提供替代方案。

+1

你可能想看看[二叉樹](http://en.wikipedia.org/wiki/Binary_tree)。這[問題](http://stackoverflow.com/questions/12205180/implementing-binary-tree-in-ruby)可能是一個開始。 – Eric

回答

1

這是一個起點:

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"], ... ] } ... } 

現在子文件夾與其父鍵相關。

相關問題