The buzzwords of the moment:

Linq for the .Net world, Ruby for the open source world.

Jon Udel wrote the following example for the .Net world to show of the nice things about Linq:

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.

Sam Ruby responded with a bit of Ruby code which does largely the same.

The .Net implementationThe Ruby implementation

XDocument doc = XDocument.Load("blog.xml");

var d  = new Dictionary<string,string>();
d.Add("2005/09","September 2005");
d.Add("2005/08","August 2005");

var a = new string[] { "greasemonkey", "ajax" };

var query =
  from
    item in doc.Descendants("item"),
    key in d.Keys,
    tag in a
  where item.Element("date").Value.Contains(key) &&
        item.Element("tags").Value.Contains(tag)
  orderby
    (string) item.Element("date") descending
  select new XElement("item",
    new XElement("month",d[key]),
    item.Element("date"),
    item.Element("title"),
    item.Element("tags"));

foreach (var result in query)
  Console.WriteLine(result);

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

 

The output:

<item>
   <month>September 2005</month>
   <date>2005/09/26</date>
   <title>A channel changer for the Bloglines river of news</title>
   <tags>greasemonkey bloglines</tags>
</item>
<item>
   <month>August 2005</month>
   <date>2005/08/10</date>
   <title>Architecture of participation, architecture of control</title>
   <tags>firefox greasemonkey security opensource</tags>
</item>

The moral of this comparison is that there might already be an answer to this problem... available today.
That being said the Ruby code doesn't have intellisence while coding, this in contrast to the .Net code.

There are also some other small differences, you can read about these in the original articles:

.Net code origin.
Ruby code origin.

 

Leave a Comment

(required) 
(required) 
(optional)
(required)