Skip to content

Instantly share code, notes, and snippets.

@davidrenne
Created December 3, 2012 13:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidrenne/4195122 to your computer and use it in GitHub Desktop.
Save davidrenne/4195122 to your computer and use it in GitHub Desktop.
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