gpt4 book ai didi

ruby-on-rails - ruby 从数组中添加字符串

转载 作者:行者123 更新时间:2023-12-03 18:34:12 24 4
gpt4 key购买 nike

我正在用 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"]

最佳答案

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

require 'pathname'

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

关于ruby-on-rails - ruby 从数组中添加字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63556958/

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