按匹配值对字符串进行分组(字符串是链接路径)?

时间:2013-11-11 23:47:14

标签: javascript ruby-on-rails ruby

我有一些链接,我从我的Github API中提取到我的Rails应用程序中的视图。目标是让这些链接最终按文件夹分组(如果它们是嵌套的),并且只有它们没有任何子项时才是唯一的并且是独立的。

以下是我从Github回购中获得的一个示例:

app
app/assets
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

这些链接中的http://部分总是相同的,我现在只是将它连接在一起,以使路径绝对。

如何按文件夹对它们进行分组?我会想象一些字符串方法,但我不确定最好的方法是什么。另外,Ruby或JavaScript是最好的解决方案吗?

1 个答案:

答案 0 :(得分:2)

这是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下的app),你希望值数组包含基本名而不是完整路径(application.css而不是{ {1}}),您可以使用:

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? }