ruby 从数组中添加字符串

pau*_*ula 4 ruby ruby-on-rails

我正在用 ruby​​ 构建一个简单的面包屑,但我不确定如何真正实现我的逻辑。

假设我有一组取自我的单词,request.path.split("/) ["", "products", "women", "dresses"] 我想将字符串推入另一个数组,所以最后我有["/", "/products", "products/women", "products/women/dresses"],我将使用它作为我的面包屑解决方案。

我不擅长红宝石,但现在我想出了以下方法

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 
Run Code Online (Sandbox Code Playgroud)

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

Ste*_*fan 6

RubyPathname有一些基于字符串的路径操作实用程序,例如ascend

require 'pathname'

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