Here’s some light Friday fun… When working in ruby with regular expressions on Arrays of Strings, I get so tired of doing this:
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:
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:
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?
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:
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'))
Advertisements