Wednesday, September 20, 2006

A Java vs. Ruby example

Here’s some Java code I borrowed and wrote to extract multi-word tags surrounded by quotes from a string and add them to a list
// Now extract all multi-word keywords delimited by spaces
// but not surrounded by quotes
p = Pattern.compile("\"(.*?)\"\\s*");
m = p.matcher(keywordString);
sb = new StringBuffer();

while (m.find()) {
// Get previous match and add it to the keywords list
String kw =;
if (! "".equals(kw)) {
kw = kw.trim().replaceAll("\"", "");
// remove the current match from the string
// and thus from consideration
m.appendReplacement(sb, "");
keywordString = sb.toString();
Here’s the Ruby equivalent
keywordString.gsub!(/\\"(.*?)\"\s*\/) {keywords << $1.strip}
It’s not the lines of code (although the Ruby code is 1/3 the size) that I notice so much as the unintuitive Java API. appendReplacement? What’s that? Verbosity does not add clarity to the Java and the lack thereof does not detract from clarity for Ruby.