O
O
Ord EO2021-04-07 12:07:05
ruby
Ord EO, 2021-04-07 12:07:05

How to add an array to itself n number of times with a specific element in ruby?

There is an array = ['one', 'two', 'three']
there is counter- can be any positive integer
We need to get such a result, with, supposecounter = 3

[ 'counter 1', 'one',  'two',  'three', 'counter 2', 'one',  'two',  'three', 'counter 3', 'one',  'two',  'three']

Tried to do so
new_arr = []
counter.each_with_index do |arr, index|
new_arr << arr.unshift("counter #{index}")
end


But the problem is that it each_with_indexdoes not work with a number, maybe there is some way to fix this or another solution that can be applied, tell a beginner.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-04-07
@OrdeO

Array.new(counter){|i| [ "counter #{i + 1}", arr ]}.flatten

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question