Here’s some light Friday fun… When working in ruby with regular expressions on Arrays of Strings, I get so tired of doing this:

1 my_array.map! { |item|
2     item.gsub(/delete this/, '')
3 }

Can’t we just give the regex to the array, and let it figure it out? How about this:

1 class Regexp
2    def stripper
3       lambda { |s| s.gsub(self, '') }
4    end
5 end
6 
7 my_array.map!(&/delete this/.stripper)

We can generalize it to use any string as the replacement:

 1 class Regexp
 2    def swapper(new_s)
 3       lambda { |s| s.gsub(self, new_s) }
 4    end
 5 
 6    def stripper
 7       swapper ''
 8    end
 9 end
10 
11 my_array.map!(&/delete this/.stripper)
12 my_array.map!(&/replace this/.swapper('with this'))

Which gets me thinking…what if we want to extract text by a regexp?

1 class Regexp
2    def scanner
3       lambda { |s| s.scan(self) }
4    end
5 end
6 
7 my_array.map(&/[find pattern]/.scanner)

What else can we do with regular expressions?

As a bonus, this translates nicely into JavaScript, too:

 1 RegExp.prototype.swapper = function(new_s) {
 2    re = this
 3    return function(s) {
 4       return s.replace(re, new_s)
 5    }
 6 }
 7 
 8 RegExp.prototype.stripper = function() {
 9    return this.swapper('')
10 }
11 
12 // Don't forget those closing parens...
13 my_array.map(/delete this/.stripper())
14 my_array.map(/replace this/.swapper('with this'))