Skip to content

Instantly share code, notes, and snippets.

@stan
Created August 31, 2010 06:19
Show Gist options
  • Save stan/558632 to your computer and use it in GitHub Desktop.
Save stan/558632 to your computer and use it in GitHub Desktop.
# 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