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
2
3
my_array.map! { |item|
    item.gsub(/delete this/, '')
}

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

1
2
3
4
5
6
7
class Regexp
   def stripper
      lambda { |s| s.gsub(self, '') }
   end
end

my_array.map!(&/delete this/.stripper)

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

1
2
3
4
5
6
7
8
9
10
11
12
class Regexp
   def swapper(new_s)
      lambda { |s| s.gsub(self, new_s) }
   end

   def stripper
      swapper ''
   end
end

my_array.map!(&/delete this/.stripper)
my_array.map!(&/replace this/.swapper('with this'))

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

1
2
3
4
5
6
7
class Regexp
   def scanner
      lambda { |s| s.scan(self) }
   end
end

my_array.map(&/[find pattern]/.scanner)

What else can we do with regular expressions?

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
RegExp.prototype.swapper = function(new_s) {
   re = this
   return function(s) {
      return s.replace(re, new_s)
   }
}

RegExp.prototype.stripper = function() {
   return this.swapper('')
}

// Don't forget those closing parens...
my_array.map(/delete this/.stripper())
my_array.map(/replace this/.swapper('with this'))