The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Fun with Enumerable::Enumerator

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Kurtis Seebaldt

Posts: 10
Nickname: kseebaldt
Registered: Nov, 2007

Kurtis Seebaldt is a Ruby developer at ThoughtWorks
Fun with Enumerable::Enumerator Posted: Feb 23, 2008 11:22 PM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Kurtis Seebaldt.
Original Post: Fun with Enumerable::Enumerator
Feed Title: Kurtis Seebaldt
Feed URL: http://kseebaldt.blogspot.com/feeds/posts/default
Feed Description: Ruby, consulting, smiting
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Kurtis Seebaldt
Latest Posts From Kurtis Seebaldt

Advertisement
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)



Read: Fun with Enumerable::Enumerator

Topic: "They shouldn’t be too perfect; perfect means shallow and unreal and fatally uninteresting." Previous Topic   Next Topic Topic: Rails and ProxyPreserveHost

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use