Skip to content

Instantly share code, notes, and snippets.

@wtnabe
Created March 1, 2009 07:40
Show Gist options
  • Save wtnabe/72258 to your computer and use it in GitHub Desktop.
Save wtnabe/72258 to your computer and use it in GitHub Desktop.
Array#classify for String elements using Regexp
# -*- 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