# Current Temperature (#68)

**URL:** <https://www.ruby-forum.com/t/current-temperature-68/74404>\
**Category:** Ruby\
**Created:** [February 27, 2006, 10:26pm UTC](https://www.ruby-forum.com/t/current-temperature-68/74404 "2006-02-27T22:26:54Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![davidtl](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/35a633/32.png) [@davidtl](https://www.ruby-forum.com/u/davidtl)\
**Post date:** [February 27, 2006, 10:26pm UTC](https://www.ruby-forum.com/t/current-temperature-68/74404/1 "2006-02-27T22:26:54Z")

</div>

require ‘uri’  
require ‘open-uri’  
require ‘rexml/document’

class Weather  
attr\_reader :location, :temperature, :unit

def initialize(zip\_or\_city, unit=‘f’)  
raise “Error: Unit must be ‘C’ or ‘F’.” unless unit =~ /^[cf]$/i  
id = get\_id(zip\_or\_city)  
url =  
“[http://xml.weather.yahoo.com/forecastrss/#{id}\_#{unit.downcase}.xml](http://xml.weather.yahoo.com/forecastrss/#%7Bid%7D_#%7Bunit.downcase%7D.xml)”  
xml = open(url) { |f| f.read }  
doc = REXML::Document.new(xml)  
@temperature =  
doc.elements[‘/rss/channel/item/yweather:condition/@temp’].to\_s.to\_i  
@unit = unit.upcase  
end

private  
def get\_id(location)  
location = URI.escape(location)  
url = “[National and Local Weather Radar, Daily Forecast, Hurricane and information from The Weather Channel and weather.com](http://xoap.weather.com/search/search?where=#%7Blocation%7D)”  
xml = open(url) { |f| f.read }  
doc = REXML::Document.new(xml)  
locations = doc.elements.to\_a(“/search/loc”)  
raise “Cannot find the location.” if locations.size \<= 0  
# raise "Please more specific:\n#{locations.map {|e|  
e.text}_“\n”}" if locations.size \> 1  
 @location = locations[0].text.sub(/\s_(\d+)\s\*$/, ‘’)  
locations[0].attributes[‘id’]  
end  
end

if **FILE** == $0  
if ARGV.size \<= 0 || (ARGV[1] && ARGV[1] !~ /^[cf]$/i)  
puts “Usage: #$0 city\_or\_zip\_code [c|f]”  
exit(1)  
end

begin  
w = 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**

> **[乐享彩票-welcome登录](http://www.doublegifts.com)**
>
> 乐享彩票【91682.com】国内最安全、彩种最齐全的每日彩票平台，提供★乐彩彩票\_乐发彩票app下载★网站、登录、下载、网址、注册、投注等功能，彩种有快3、双色球、大乐透、11选5等二十多种。
