简体   繁体   中英

How to create multiple links from a single array of strings Rails - Ruby

I know it might seem simple but I've tried to create multiple links from this array in Rails

array = ["/uploads/content/attachment/folder/file1.pdf/file2.pdf/file3.pdf"]

What I want to do is create a link for file1 and another for file2 and so on.

I've tried to use the join and separate method, image_tag, content_tag and many many different cycles in Rails but every single one ends up like the link above.

Something like this if I understood correctly:

array = ["/uploads/content/attachment/folder/file1.pdf/file2.pdf/file3.pdf"]
base = "https://www.example.com/" #the first part of the link, that's same for all links

links = array.first[1..-1].split("/").map{|a| base + a}
puts links
#=>  "https://www.example.com/uploads",
#    "https://www.example.com/content",
#    "https://www.example.com/attachment",
#    "https://www.example.com/folder",
#    "https://www.example.com/file1.pdf",
#    "https://www.example.com/file2.pdf",
#    "https://www.example.com/file3.pdf"

The question is not clear.

I assume the array will be like this:

array = [
  "/uploads/content/attachment/folder/file1.pdf/file2.pdf/file3.pdf",
  "/uploads/content/attachment/folder/file12.pdf/file23.pdf/fildf34.pdf",
  "/foo/boo/folder/file1.doc/file2.docx/file11.pdf"
]

It splits links for folder/

links = array.map{ |a| a.split('folder/') }.flat_map do |path, files|
  files.split('/').map{ |file| path + "folder/" + file }
end

p links
#=> [
      "/uploads/content/attachment/folder/file1.pdf",
      "/uploads/content/attachment/folder/file2.pdf",
      "/uploads/content/attachment/folder/file3.pdf",
      "/uploads/content/attachment/folder/file12.pdf",
      "/uploads/content/attachment/folder/file23.pdf",
      "/uploads/content/attachment/folder/fildf34.pdf",
      "/foo/boo/folder/file1.doc",
      "/foo/boo/folder/file2.docx",
      "/foo/boo/folder/file11.pdf"
    ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM