4

I would like to split my array in the following way:

current_arr = [1,2,3,4,5]

new_arr = [[1,2,3], [2,3,4], [3,4,5]]

#each_slice and #combination are close to what I want but not quite.
How could I split my array as in the example?

2
  • 1
    Why the rush to select an answer. You don't want to see others? Commented Jan 17, 2019 at 18:52
  • The question is not clear. There are different logics (which would lead to different results given if parameters were changed) to create the output you want. Commented Jan 18, 2019 at 3:51

2 Answers 2

6
[1,2,3,4,5].each_cons(3).to_a
#=> [[1, 2, 3], [2, 3, 4], [3, 4, 5]]

Check doc for each_cons.

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

3 Comments

@tadman: true that. I'm doing some Go now and I miss the Enumerable :)
I want to port Enumerable to everything for that reason.
@tadman, Enumerable would be a nothing-burger without Enumerator. It's the latter that's most deserving of our praise. Yes?
1

Just for fun:

ary = [1,2,3,4,5]

n = 3
(ary.size - n + 1).times.each_with_object([]) { |_, a|  a << ary.first(n); ary.rotate! }

#=> [[1, 2, 3], [2, 3, 4], [3, 4, 5]]

Comments

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.