D
David Tran
require 'uri'
require 'open-uri'
require 'rexml/document'
class Weather
attr_reader :location, :temperature, :unit
def initialize(zip_or_city, unit=3D'f')
raise "Error: Unit must be 'C' or 'F'." unless unit =3D~ /^[cf]$/i
id =3D get_id(zip_or_city)
url =3D "http://xml.weather.yahoo.com/forecastrss/#{id}_#{unit.downcase=
}.xml"
xml =3D open(url) { |f| f.read }
doc =3D REXML:ocument.new(xml)
@temperature =3D
doc.elements['/rss/channel/item/yweather:condition/@temp'].to_s.to_i
@unit =3D unit.upcase
end
private
def get_id(location)
location =3D URI.escape(location)
url =3D "http://xoap.weather.com/search/search?where=3D#{location}"
xml =3D open(url) { |f| f.read }
doc =3D REXML:ocument.new(xml)
locations =3D doc.elements.to_a("/search/loc")
raise "Cannot find the location." if locations.size <=3D 0
# raise "Please more specific:\n#{locations.map {|e|
e.text}*"\n"}" if locations.size > 1
@location =3D locations[0].text.sub(/\s*\(\d+\)\s*$/, '')
locations[0].attributes['id']
end
end
if __FILE__ =3D=3D $0
if ARGV.size <=3D 0 || (ARGV[1] && ARGV[1] !~ /^[cf]$/i)
puts "Usage: #$0 city_or_zip_code [c|f]"
exit(1)
end
begin
w =3D Weather.new(ARGV[0], ARGV[1] || 'f')
puts "The temperature in #{w.location} is #{w.temperature} degress
#{w.unit}."
rescue
puts "Information for #{ARGV[0]} was not found or unavailable."
end
end
__END__
www.doublegifts.com
require 'open-uri'
require 'rexml/document'
class Weather
attr_reader :location, :temperature, :unit
def initialize(zip_or_city, unit=3D'f')
raise "Error: Unit must be 'C' or 'F'." unless unit =3D~ /^[cf]$/i
id =3D get_id(zip_or_city)
url =3D "http://xml.weather.yahoo.com/forecastrss/#{id}_#{unit.downcase=
}.xml"
xml =3D open(url) { |f| f.read }
doc =3D REXML:ocument.new(xml)
@temperature =3D
doc.elements['/rss/channel/item/yweather:condition/@temp'].to_s.to_i
@unit =3D unit.upcase
end
private
def get_id(location)
location =3D URI.escape(location)
url =3D "http://xoap.weather.com/search/search?where=3D#{location}"
xml =3D open(url) { |f| f.read }
doc =3D REXML:ocument.new(xml)
locations =3D doc.elements.to_a("/search/loc")
raise "Cannot find the location." if locations.size <=3D 0
# raise "Please more specific:\n#{locations.map {|e|
e.text}*"\n"}" if locations.size > 1
@location =3D locations[0].text.sub(/\s*\(\d+\)\s*$/, '')
locations[0].attributes['id']
end
end
if __FILE__ =3D=3D $0
if ARGV.size <=3D 0 || (ARGV[1] && ARGV[1] !~ /^[cf]$/i)
puts "Usage: #$0 city_or_zip_code [c|f]"
exit(1)
end
begin
w =3D Weather.new(ARGV[0], ARGV[1] || 'f')
puts "The temperature in #{w.location} is #{w.temperature} degress
#{w.unit}."
rescue
puts "Information for #{ARGV[0]} was not found or unavailable."
end
end
__END__
www.doublegifts.com