Ruby将数组中的字符串相加

4

我正在使用Ruby构建一个简单的面包屑导航,但是我不确定如何实现我的逻辑。

假设我有一个单词数组,这些单词来自我的request.path.split("/)["", "products", "women", "dresses"] 我想把这些字符串推入另一个数组中,最终得到["/", "/products", "products/women", "products/women/dresses"],并将其用作我的面包屑解决方案。

虽然我不擅长Ruby,但我目前想到了以下代码:

cur_path = request.path.split('/')

cur_path.each do |link|
  arr = []
  final_link = '/'+ link
  if cur_path.find_index(link) > 1
    # add all the previous array items with the exception of the index 0
  else
    arr.push(final_link)
  end
end 

结果应该是["/", "/products", "/products/women", "/products/women/dresses"]

4个回答

6

Ruby的Pathname提供了一些基于字符串的路径操作工具,例如ascend

require 'pathname'

Pathname.new('/products/women/dresses').ascend.map(&:to_s).reverse
#=> ["/", "/products", "/products/women", "/products/women/dresses"]

3
这是我最简单的解决方案:
a = '/products/women/dresses'.split('/')
a.each_with_index.map { |e,i| e.empty? ? '/' : a[0..i].join('/')  }

2

这是使用Enumerable#each_with_objectEnumerable#each_with_index的另一种选项:

ary = '/products/women/dresses'.split('/')
ary[1..].map
        .with_index
        .with_object([]) { |(folder, idx), path| path << [path[idx-1], folder].join('/') }.unshift('/')

或者也可以:
(ary.size - 1).times.map { |i| ary.first(i + 2).join('/') }.unshift('/')

2

使用 mapwith_index,可以这样实现:

arr = ["", "products", "women", "dresses"]
arr.map.with_index { |item, index| "#{arr[0...index].join('/')}/#{item}" }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接