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
end


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:

Enumerable::Enumerator.new(REXML::XPath, :each, @document.root,  "//list/items").collect(&:text)



3 comments:

Anonymous said...

Would the following not work for you?

items = []
@document.root.each_element("//list/items") do |element|
  items << element.text
end

Anonymous said...

Or indeed, since this uses the Elements class, which is enumerable:

@document.root.elements.collect("//list/items") { |e| e.text }

Kurtis Seebaldt said...

Yes, that would work, too. I forgot about Elements being Enumerable.