这是 Ruby 中的一种简单方法,假设您将列表放在一个名为 的数组中paths
:
grouped = paths.group_by { |p| File.dirname(p) }
这将产生一个包含以下内容的哈希:
{"."=>["app"],
"app"=>["app/assets", "app/controllers"],
"app/assets"=>
["app/assets/images", "app/assets/javascripts", "app/assets/stylesheets"],
"app/assets/images"=>["app/assets/images/.keep"],
"app/assets/javascripts"=>
["app/assets/javascripts/ace.js",
"app/assets/javascripts/application.js",
"app/assets/javascripts/editor.js.coffee"],
"app/assets/stylesheets"=>
["app/assets/stylesheets/application.css",
"app/assets/stylesheets/editor.css.scss"],
"app/controllers"=>
["app/controllers/application_controller.rb", "app/controllers/concerns"]}
如果您想摆脱目录元素(例如app/assets
under app
),并且希望值数组包含基本名称而不是完整路径(application.css
而不是app/assets/stylesheets/application.css
),您可以使用:
grouped.each do |dir, paths|
# If the path is also a hash key in "grouped", it must be a directory
paths.delete_if { |path| grouped.has_key? path }
# Replace each element with its basename
paths.map! { |path| File.basename(path) }
end
最后,省略空目录:
grouped.delete_if { |dir, paths| paths.empty? }
所有这些都会给你留下:
{"app/assets/images"=>[".keep"],
"app/assets/javascripts"=>["ace.js", "application.js", "editor.js.coffee"],
"app/assets/stylesheets"=>["application.css", "editor.css.scss"],
"app/controllers"=>["application_controller.rb", "concerns"]}