Wolf_Tru
Wolf_Tru

Reputation: 563

How to iterate over consecutive elements

I'm looking for a method that is similar to Array#combination, but the order matters.

Given this input:

array = ['a','b','c','d','e']

I'd like to get:

[['a','b','c'],['b','c','d'],['c','d','e']]

I'm trying to find the method that does this:

array = ['a','b','c','d','e']
x,a = 3,[] 

until x > (ary.size) do 
  a += (0.upto(ary.size - x).map{|i|  ary[i..(x-1)+i]} )
  x += 1 
end

Upvotes: 1

Views: 547

Answers (1)

the Tin Man
the Tin Man

Reputation: 160551

The Enumerable documentation is your friend:

array = ['a','b','c','d','e']
array.each_cons(3).to_a
# => [["a", "b", "c"], ["b", "c", "d"], ["c", "d", "e"]]

each_cons(n) { ... }

Iterates the given block for each array of consecutive elements. If no block is given, returns an enumerator.

Upvotes: 6

Related Questions