My solution uses yahoo weather like another of the solutions here. It's
easy to use with US zip codes, but for international cities you have to
know the yahoo weather location id. I looked around for a big list of
these but couldn't find it. Anyways it would be nice to have some sort
of searching mechanism to turn a city name into a location id.
Also I used rexml to parse the rss feed. I tried to use the rss library,
but couldn't figure out how to pull out the 'yweather' tags.
Anyways, fun quiz. I enjoyed it a lot.
-----Jay Anderson
require 'rexml/document'
require 'open-uri'
#Returns a hash containing the location and temperature information
#Accepts US zip codes or Yahoo location id's
def yahoo_weather_query(loc_id, units)
h = {}
open("http://xml.weather.yahoo.com/forecastrss?p=#{loc_id}&u=#{units}")
do |http|
response = http.read
doc = REXML::Document.new(response)
root = doc.root
channel = root.elements['channel']
location = channel.elements['yweather:location']
h[:city] = location.attributes["city"]
h[:region] = location.attributes["region"]
h[:country] = location.attributes["country"]
h[:temp] =
channel.elements["item"].elements["yweather:condition"].attributes["temp"]
end
h
end
if ARGV.length < 1 then
puts "usage: #$0 <location> [f|c]"
exit
end
loc_id = ARGV[0]
units = (ARGV[1] || 'f').downcase
units = (units =~ /^(f|c)$/) ? units : 'f'
#An improvement would be to allow searches for the yahoo location id
#loc_id = yahoo_loc_search(loc_id)
weather_info = yahoo_weather_query(loc_id, units)
city = weather_info[:city]
region = weather_info[:region]
country = weather_info[:country]
temp = weather_info[:temp]
puts "The temperature in #{city}, #{region}, #{country} is #{temp}
degrees #{units.upcase}"
--
Posted via http://www.ruby-forum.com/.