nosewheelie

Technology, mountain biking, politics & music.

Archive for the ‘Ruby’ tag

Nobody *ever* uses map, et. al… (example 1)

with 4 comments

Inspired by Daniel’s comment on Tony’s blog, I figured I’d start documenting the times I use “functional” constructs in my everyday work.

Consider this piece of XML, returned from an external web service:

<suggestions>
  <suggestion>
    <suggestion>paddington, NSW</suggestion>
    <location>true</location>
  </suggestion>
  <suggestion>
    <suggestion>paddington, QLD</suggestion>
    <location>true</location>
  </suggestion>
</suggestions>

Perform the following:

  1. Parse out each suggestion, turn it into an instance of Suggestion;
  2. Capitalise the first letter;
  3. Sort by name;
  4. Remove duplicates;

Here’s some Ruby code that does this, parsing by Hpricot:

class SuggestionsParser
  def self.parse(node)
    suggestions = node.search("//suggestions/suggestion").map do |s|
      Suggestion.new(s.at("suggestion").inner_text.capitalise_first_letter, s.at("location").inner_text == "true")
    end
    suggestions.sort.uniq
  end
end

But of course nobody ever does this…

Written by Tom Adams

July 2nd, 2008 at 2:14 pm

Posted in Functional, Languages, Ruby

Tagged with , , ,