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:

  • @rbazinet Dude, a Dell Latitude D820? That's my work laptop! I'm pretty "meh" about it. 33 minutes ago
  • @jpmccu "Clutter [is] a result of...excessive attachment." I think this relates to projects too. So many things out there to do! 2 days ago
  • @wigu If we say we LIKE the teeth, does that mean they'll go away sooner? 2 days ago
  • @dchec Invite them behind the counter, and move the event to a small town. You never know. 6 days ago
  • @kdaigle Where's the new digs again? Congrats on the move! 6 days ago

I’m a BackPack fan

Backpack

Categories