Ruby is Very Concise

For a work project, we needed the locations of all US Apple Stores. I couldn’t find a list, so I decided to “scrape” Apple’s site for the addresses. Less than 20 lines of Ruby did the trick:

#! /usr/bin/ruby

require 'open-uri'

open("") do |file|
end.split("<a href=").map do |seg| 
  (match = seg.match(/"\/retail\/([a-z0-9]+)/)) ? match[1] : nil
end.compact.each do |loc|
  contents = open("{loc}/") do |file|
  puts [
    /\<span class="street-address"\>(.*)\<\/span\>/,
    /\<span class="locality"\>(.*)\<\/span\>,/,
    /\<span class="region"\>(.*)\<\/span\> /,
    /\<span class="postal-code"\>(.*)\<\/span\>/
  ].map { |pat| contents.match(pat)[1] }.join(", ")

I’m always wary of using temporary variables (in this case, match and contents) but I couldn’t figure out a way to avoid them.

Tags: Technical

Updated at: 29 March 2011 3:03 PM