gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:08:14 25 4
gpt4 key购买 nike

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

以下是我从 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 是最好的解决方案?

最佳答案

这是 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 下的 app/assets),并且希望值数组包含基本名称而不是完整路径( 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"]}

关于javascript - 按匹配值对字符串进行分组(字符串是链接路径)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19918276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com