Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

James Robertson http://www.r0bertson.co.uk

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

Receiving REXML's *processed* children from the XPATH

This script is almost the same as 'Receiving REXML's children from the XPath' [dzone.com], however rather than pass back the whole XML node I simply wanted the node's text value. Here's how I did it:

   1  a_a = doc_a.root.elements.each('records/tag/keyword'){}.map { |node| node.text}

=> ["curtains", "in", "the", "window", "I", "said", "on", "chimney"]

see also: Modify an Array's content using map [dzone.com]

update: 5-Sep-08
Here's a similar script which creates a hash from the nodes's keyword and count elements.
   1  c_c = doc_a.root.elements.each("records/tag"){}.map { |node| 
   2    akeyword_count = Array.new
   3    akeyword_count << node.elements['keyword'].text
   4    akeyword_count << node.elements['count'].text
   5    akeyword_count
   6  }.flatten.to_h


=> {"curtains"=>"2", "window"=>"1", "in"=>"1", "the"=>"2", "chimney"=>"1", "on"=>"1", "said"=>"1", "I"=>"1"}

Note: This code implements the extended Array method 'to_h' from Convert an array to a hash [dzone.com]

Modify an Array's content using map

Using the Array method "map" copies an array with the contents modified from the associated block.

   1  vowels = ["a", "e","i", "o", "u"]
   2  words = vowels.map do |vowel|
   3    "p#{vowel}t"
   4  end

=> ["pat", "pet", "pit", "pot", "put"]

Reference: Vitamin Features ยป The Basics of Ruby Arrays [thinkvitamin.com]

note: The Array method "collect" performs exactly the same routine as "map".
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS