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("http://www.apple.com/retail/storelist") do |file|
file.read
end.split("<a href=").map do |seg|
(match = seg.match(/"\/retail\/([a-z0-9]+)/)) ? match[1] : nil
end.compact.each do |loc|
contents = open("http://www.apple.com/retail/#{loc}/") do |file|
file.read
end
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(", ")
end
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.