module Enumerable

instance methods

Enumerable#each_cluster n = 2
Enumerable#each_with_neighbors n = 1, empty = nil

Both methods iterate over a collection of arrays whose elements are drawn in sequence from the original collection.

In the case of each_cluster, the iteration yields all contiguous subsequences of length n. If the argument to each_cluster is 0 or larger than the size of the collection, the iteration yields no values.

In the case of each_with_neighbors, the iteration yields one sequence for each element x of the collection. The yielded sequence includes the n elements before and after x. Elements out of bounds are filled with empty. The first argument can be any nonnegative integer.

examples

require 'enum/cluster'

(0..5).each_with_neighbors { |x| p x }

# prints: 
# [nil, 0, 1]
# [0, 1, 2]
# [1, 2, 3]
# [2, 3, 4]
# [3, 4, 5]
# [4, 5, nil]

[1,2,3,4].each_with_neighbors(8, 0) { |x| p x }

# prints: 
# [0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 0, 0]
# [0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 0, 0, 0]
# [0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0]
# [0, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0]

('a'..'g').each_cluster(5) { |x| p x.join '' }

# prints: 
# "abcde"
# "bcdef"
# "cdefg"

See the end of the source file for more examples.

version

Enumerable tools 1.5

The current version of this software can be found at http://redshift.sourceforge.net/enum .

license

This software is distributed under the Ruby license. See http://www.ruby-lang.org.

author

Joel VanderWerf, vjoel@users.sourceforge.net