Created
March 1, 2009 07:40
-
-
Save wtnabe/72258 to your computer and use it in GitHub Desktop.
Array#classify for String elements using Regexp
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
# -*- coding: utf-8 -*- | |
class Array | |
# | |
# classift( /()/ ) | |
# | |
# [ | |
# [grouped by same \1], | |
# [grouped by same \1], | |
# [grouped by same \1], | |
# [others] | |
# ] | |
# | |
# two-clause BSD | |
# | |
def classify( re, strict = false ) | |
c = {} | |
o = [] | |
k = [] | |
self.each { |e| | |
e.match( re ) | |
if ( $1 ) | |
if ( !c.has_key?( $1 ) ) | |
k << $1 | |
c[$1] = [] | |
end | |
c[$1] << e | |
else | |
o << e | |
end | |
} | |
vals = [] | |
vals += k.map { |e| c[e] } | |
return ( strict ) ? vals : vals + o | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment