4

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"]

4 Answers 4

6

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"]
Sign up to request clarification or add additional context in comments.

Comments

3

This is my simplest solution:

a = '/products/women/dresses'.split('/')
a.each_with_index.map { |e,i| e.empty? ? '/' : a[0..i].join('/')  }

Comments

2

Using map and with_index it can be done like this:

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

Comments

2

This is another option using Enumerable#each_with_object and Enumerable#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('/')

Or also:

(ary.size - 1).times.map { |i| ary.first(i + 2).join('/') }.unshift('/')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.