Make an array from list where first element of the array is the first element in list

Viewed 40

I am very new to ruby so excuse me if this is a basic question.

I have a list that looks like this:

    [name, max, john, raj, sam]

And i want to make a new array that will look like this:

    [[name, max], [name, john], [name, raj], [name, sam]]

Here is what i am trying to do:

    row.xpath('td').each_with_index do |cell, index|
     if index == 0
      tarray['name'] << cell.text
     else
      tarray['values'] << cell.text
    end

I know i am doing it wrong because when i have ['name'] it will not be logically possible to have ['values'] Please advice me on how i can achieve this using the best method.

2 Answers

You can take the first value (:name) and get its product with every remaning element by using Array#product:

array = [:name, :max, :john, :raj, :sam]
p [array[0]].product(array[1..-1])
# [[:name, :max], [:name, :john], [:name, :raj], [:name, :sam]]

Array#product is better, but you can also use Array#zip:

ary = [:a, :b, :c, :d]

([ary.first]*(ary.size-1)).zip ary[1..]
#=> [[:a, :b], [:a, :c], [:a, :d]]

Or also:

ary.then { |a, *rest| ([a] * rest.size).zip rest }

But yes, product is cleaner:

ary.then { |a, *rest| [a].product rest }
Related