Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby add strings from array

I am building a simple breadcrumb in ruby but I am not sure how to really implement my logic.

Let's say I have an array of words that are taken from my request.path.split("/) ["", "products", "women", "dresses"] I want to push the strings into another array so then in the end I have ["/", "/products", "products/women", "products/women/dresses"] and I will use it as my breadcrumb solution.

I am not good at ruby but for now I came up with following

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 

The results should be ["/", "/products", "/products/women", "/products/women/dresses"]

like image 233
paula Avatar asked Dec 11 '22 00:12

paula


2 Answers

Ruby's Pathname has some string-based path manipulation utilities, e.g. ascend:

require 'pathname'

Pathname.new('/products/women/dresses').ascend.map(&:to_s).reverse
#=> ["/", "/products", "/products/women", "/products/women/dresses"]
like image 69
Stefan Avatar answered Dec 27 '22 15:12

Stefan


This is my simplest solution:

a = '/products/women/dresses'.split('/')
a.each_with_index.map { |e,i| e.empty? ? '/' : a[0..i].join('/')  }
like image 35
eikes Avatar answered Dec 27 '22 16:12

eikes