Archive for February, 2008

Regular Expressions into lambdas: swapper, stripper, scanner

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'))

Counting On Your Fingers

If I ever have kids, I’ll teach them to count on their fingers. In binary. “Pff, 10? I can reach 1023!”

Of course, they’ll probably get carpal tunnel from all the low-digit activity.


Say Hello

danbernier [at] gmail [dot] com
Twitter @danbernier
Hartford.rb
LinkedIn

Tweeting:

  • Trying f.lux: http://stereopsis.com/flux/ Just watched a rather noticeable change as sunset hit. Weird, but cool. 1 day ago
  • My first day limiting gmail, google rss, gwave, twitter, google calendar, & outlook to only 3 times a day. Went well, I like it! 1 day ago
  • When MS sunsets XP, companies will get Win7, with IE8. Will that destroy IE6's market share? Will that solve our problems? 4 days ago
  • @bdowden Well, no, but clearing off the muck at least lets you REALIZE it's a car. Which is worth knowing. 6 days ago
  • Taming dependencies helps the real structure emerge. It's like cleaning swamp slime off a submerged car frame. 6 days ago

I’m a BackPack fan

Backpack

Categories