Created
August 31, 2010 06:19
-
-
Save stan/558632 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# http://apidock.com/rails/Enumerable/group_by#508-Array-clustering | |
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 | |
# Document.all.cluster{|document| [document.created_on, document.type]} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment