Sunday, April 29, 2007

emacs love

I was working on some ruby code just now. I had a hash with keys that were capitalized words, such as:

comp << l['Address'] unless l['Address'].empty?
comp << l['City'] unless l['City'].empty?
comp << l['State'] unless l['State'].empty?
comp << l['Zip'] unless l['Zip'].empty?
comp << l['Country'] unless l['Country'].empty?

but I made some changes so that all of the keys would now be lowercase and turned into symbols. Basically I wanted the output to look like this:

comp << l[:address] unless l[:address].empty?
comp << l[:city] unless l[:city].empty?
comp << l[:state] unless l[:state].empty?
comp << l[:zip] unless l[:zip].empty?
comp << l[:country] unless l[:country].empty?

With a little help from an ex coworker's blog, I was able to achieve this using the following regular expression:

M-x replace-regexp
l[:\,(downcase \1)\2]

Note that the '\,' (backslash-comma) combination escapes the lisp command that is part of the replacement text.
I never ceased to be amazed by the power of emacs. I'm still decades away from being able to develop a webservice in lisp. :)

No comments: