1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
require 'rubygems' require 'functor' class Array =begin usage: matches, non-matches = arr.split_with exp # where [Regexp, Proc, Array, Integer].include? exp =end def split_with(exp = nil, &block) @_split_with_functor ||= Functor.new do given(Regexp, Array) {|exp, arr| arr.select {|x| x =~ exp}} given(Proc, Array) {|exp, arr| arr.select {|x| exp.call(x)}} given(Array, Array) {|exp, arr| arr.select {|x| exp.include?(x)}} given(Integer, Array) {|exp, arr| arr.select {|x| x.to_i < exp}} end matches = @_split_with_functor.call(exp || block,self) [matches, self - matches] end end
Refactorings
No refactoring yet !
Jeff Berg
August 6, 2008, August 06, 2008 19:45, permalink
Like this?
1 2
arr = ['aa', 'ab', 'bb', 'bc'] arr.partition { |a| a =~ /a/ }
This started out as "wouldn't it be cool if I could split an array into two arrays based on a regexp match?" The rest may be .... something not very useful.