2

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

4
  • Are you going to combine the arrays afterwards? Commented May 28, 2017 at 21:42
  • If length of b goes into length of a, n times you can write b*n. Commented May 28, 2017 at 21:44
  • yes im going to sum each value by index. think inject method would do just fine and i set 'b' value for only 3 entries, anyway thanks for the suggestion :) Commented May 28, 2017 at 22:05
  • Is this for a cipher? Commented May 29, 2017 at 8:19

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Nice use of take.
2

I would have used Array#cycle had it been available, but since it was taken I thought I'd suggest some alternatives (the first being my fav).

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

[*b*(a.size/b.size), *b[0, a.size % b.size]]
  #=> [7, 8, 9, 7, 8, 9, 7, 8, 9, 7]    

Array.new(a.size) { |i| b[i % b.size] }
  #=> [7, 8, 9, 7, 8, 9, 7, 8, 9, 7]

b.values_at(*(0..a.size-1).map { |i| i % b.size })
  #=> [7, 8, 9, 7, 8, 9, 7, 8, 9, 7]

1 Comment

inspired by your answer, another method a.map.with_index { |_,i| b[i%b.size] }

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.