我试图用每个中包含的文件构建一个文件夹数组。所以,如果你的目录结构:在ruby中生成散列数组的快速方法?
DirA
|- FileA
\- FileB
DirB
\- FileC
而且我给出这个数组:
files = ["DirA/FileA", "DirA/FileB", "DirB/FileC"]
我试图建立这样
{DirA => [FileA, FileB], DirB => [FileC]}
散列现在我m以我认为是非Rubyish的方式进行操作(假定String具有一个定义获取父目录的方法):
h = {}
files.each do |f|
parent = f.getParentDir
if not h[parent] then h[parent] = [] end
h[parent].push f
end
有更优雅的方式吗?
你只关心直接包含在目录中的文件,而不是嵌套的文件/目录? – nneonneo
我使用提供给我的文件列表,我有兴趣通过父目录引用它们,以便我可以检查它们是否都存在。 –
如果不是h [parent],那么h [parent] = [] end'可以替换为 'h [parent] = []除非h [parent]'或者even rubier'h [parent] || = [ ]'。 –