intertwingly

It’s just data

Ruby 1.8 vs LINQ


Jon Udell: I’ve been checking out the LINQ technical preview, and it’s definitely an eye-opener. The following snippet does a three-way join across an XML data source and two CLR objects. The XML data source is the content of this blog. The objects are a dictionary of date mappings, and an array of strings. The output is constructed as XML.

As an educational exercise, I’ve converted this to Ruby

doc = REXML::Document.new open("blog.xml")
d = {"2005/09"=>"September 2005", "2005/08"=>"August 2005"}
a = ["greasemonkey", "ajax"]
 
xml = Builder::XmlMarkup.new
 
REXML::XPath.match(doc,"//item").select {|item|
 
  d.keys.find {|key| item.elements["date"].text.include? key} and
  a.find {|tag| item.elements["tags"].text.include? tag}
 
}.sort_by {|item| item.elements["date"].text}.reverse.each {|item|
 
  xml.item {
    xml.month d[d.keys.find {|key| item.elements["date"].text.include? key}]
    xml.date item.elements["date"].text
    xml.title item.elements["title"].text
    xml.tags item.elements["tags"].text
  }
 
}
 
puts xml.to_s

Things to note:

All in all, a little competition in language design is a good thing.  Ruby would do well to study LINQ.  And, of course, Perl 6 (if it ever ships) would allow third parties to design such syntaxes for themselves.