Created
December 3, 2012 13:44
-
-
Save davidrenne/4195122 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Enumerable | |
# clumps adjacent elements together | |
# >> [2,2,2,3,3,4,2,2,1].cluster{|x| x} | |
# => [[2, 2, 2], [3, 3], [4], [2, 2], [1]] | |
def cluster | |
cluster = [] | |
each do |element| | |
if cluster.last && yield(cluster.last.last) == yield(element) | |
cluster.last << element | |
else | |
cluster << [element] | |
end | |
end | |
cluster | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment