删除 Ruby 中的部分文件路径

Remove part of file path in Ruby

我正在接收一个数组作为变量

是一个例子

["/a/b/01_Sources/02_Transferred/06_CPAS/Redbull/from_MediaHouse/Transcripts/MI201711200143.xlsx", "/a/b/01_Sources/02_Transferred/06_CPAS/Redbull/from_MediaHouse/Transcripts/MI201703030110.pdf"]

以下语句创建此列表:

<%= var(file_list_array).map{|file| "<li>#{File.basename(file)}</li>"}.join("\n")%>

  • MI201711200143.xlsx
  • MI201703030110.pdf
  • 以下语句创建此列表

    <%= var(file_list_array).map{|file| "<li>#{file}</li>"}.join("\n")%>
    

  • /a/b/01_Sources/02_Transferred/06_CPAS/Redbull/from_MediaHouse/Transcripts/MI201711200143.xlsx
  • /a/b/01_Sources/02_Transferred/06_CPAS/Redbull/from_MediaHouse/Transcripts/MI201703030110.pdf
  • 但我真正想要的是:

  • /Redbull/from_MediaHouse/Transcripts/MI201711200143.xlsx
  • /Redbull/from_MediaHouse/Transcripts/MI201703030110.pdf
  • 我需要更改什么才能获得它?

    假设您的文件路径数组位于您可以执行的数组中。

    file_paths.map{|path| path.gsub(/.*(\/Redbull\/.*)/, ) }
    

    这将用 "Redbull" 目录下的任何内容替换每个项目

    或者,如果您不想预处理该列表,您可以将其放入显示代码中,但这会使您不清楚发送显示逻辑所需的内容。

    <%= var(file_list_array).map{|file| "<li>#{file.gsub(/.*(\/Redbull\/.*)/, )}</li>"}.join("\n")%>
    

    试试这个

    file_list_array[0].split("06_CPAS")[1]
    

    假设您想从 "06_CPAS" 拆分。您也可以像这样将其作为变量传递

    split_str = "06_CPAS"
    index = 0
    file_list_array[index].split(split_str)[1]