Saturday, February 23, 2008

Fun with Enumerable::Enumerator

Ruby has a nice class in the core library for turning objects with iterator methods into Enumerable objects: Enumerable::Enumerator. I discovered this class a while ago, but hadn't thought of a need for it at the time.

Recently, I was integrating with some web services and needed to parse some XML. REXML's XPath is a great tool for this. XPath has a method #each that will allow you to iterate over all the elements that match the XPath. So, to collect all the text nodes for an XPath, you could do something like this:

items = []
REXML::XPath.each(@document.root, "//list/items").each do |element|
items << element.text

XPath implements the each method, but isn't an Enumerable so it doesn't support methods like collect. Using Enumerable::Enumerator and Rails' to_proc makes this code simpler:, :each, @document.root,  "//list/items").collect(&:text)