D8daae35e495689a5f17d86f15d18eb4

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.

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 !

33763c130a29de64914e684ded67f02f

Jeff Berg

August 6, 2008, August 06, 2008 19:45, permalink

3 ratings. Login to rate!

Like this?

1
2
arr = ['aa', 'ab', 'bb', 'bc']
arr.partition { |a| a =~ /a/ }
D8daae35e495689a5f17d86f15d18eb4

rjspotter

August 6, 2008, August 06, 2008 19:54, permalink

No rating. Login to rate!

Yeah like that. *head-desk*

Your refactoring





Format Copy from initial code

or Cancel