Use Enumerable#each_cons . Below is a copy of ruby1.8.7 rdoc . It should work on ruby 1.8.7.
- each_cons (n) {...}
- each_cons (n)
Iterates this block for each array of consecutive elements. If none of the blocks is specified, an enumerator is returned.
With this, you can give an array:
['a', 'b', 'c', 'd', 'e'].each_cons(3).to_a # => ["a", "b", "c"], ["b", "c", "d"], ["c", "d", "e"]]
or do:
['a', 'b', 'c', 'd', 'e'].each_cons(3) {|previous, current, nekst| puts "#{previous} - #{current} - #{nekst}" }
If you want to index,
['a', 'b', 'c', 'd', 'e'].each_cons(3).to_a.each_with_index {|(previous, current, nekst), i| puts "#{i + 1}. #{previous} - #{current} - #{nekst}" }
You can pass an array to other enums, usually with inject :
['a', 'b', 'c', 'd', 'e'].each_cons(3).to_a.inject(''){|str, (previous, current, nekst)| str << previous+current+nekst }