Created
August 7, 2012 11:26
-
-
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
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
| %w{ a b c d e f }.split("c", "e") | |
| # => [["a", "b"], ["c", "d"], ["e", "f"]] |
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
| 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