Skip to content

Instantly share code, notes, and snippets.

@johncarney
Created August 7, 2012 11:26
Show Gist options
  • Select an option

  • Save johncarney/3284647 to your computer and use it in GitHub Desktop.

Select an option

Save johncarney/3284647 to your computer and use it in GitHub Desktop.
Split a Ruby Enumerable into chunks divided by an arbitary number of patterns
%w{ a b c d e f }.split("c", "e")
# => [["a", "b"], ["c", "d"], ["e", "f"]]
module Enumerable
def split(*pattern)
inject([[]]) do |results, item|
if pattern.first && pattern.first.match(item)
results << []
pattern.shift
end
results.last << item
results
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment