paula
paula

Reputation: 264

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

Upvotes: 4

Views: 209

Answers (4)

Stefan
Stefan

Reputation: 114138

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

Upvotes: 6

iGian
iGian

Reputation: 11183

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('/')

Upvotes: 2

Yakov
Yakov

Reputation: 3191

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

Upvotes: 2

eikes
eikes

Reputation: 5061

This is my simplest solution:

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

Upvotes: 3

Related Questions