Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to duplicate value of array in ruby

Tags:

ruby

I have two arrays of integers, e.g.

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
b = [7, 8, 9]

I would like to repeatedly duplicate the value of 'b' to get a perfectly matching array lengths like this:

   a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]   
   b = [7, 8, 9, 7, 8, 9, 7, 8, 9, 7]

We can assume that a.length > b.length

like image 744
nubitol Avatar asked Feb 06 '26 09:02

nubitol


1 Answers

Assuming you mean

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
b = [7, 8, 9]

then you can do:

b.cycle.take(a.length) #=> [7, 8, 9, 7, 8, 9, 7, 8, 9, 7]

<script src="//repl.it/embed/JJ3x/2.js"></script>

See Array#cycle and Enumerable#take for more details.

like image 88
Sagar Pandya Avatar answered Feb 08 '26 03:02

Sagar Pandya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!