How to write a command line tool to get the weather by zip code
suggest changeThis walks through a command-line tool that prints the temperature for a ZIP code. Start with a weather method. It needs the yahoo_weatherman gem (gem install yahoo_weatherman). That gem talks to an old Yahoo API and may no longer return data.
require 'yahoo_weatherman'
def weather(zip_code)
client = Weatherman::Client.new
client.lookup_by_location(zip_code).condition['temp']
end
The method returns the temperature for a ZIP code. To make it a command-line tool, read the arguments from ARGV. tool argument other_argument sets ARGV to ['argument', 'other_argument'].
#!/usr/bin/ruby
require 'yahoo_weatherman'
def weather(zip_code)
client = Weatherman::Client.new
client.lookup_by_location(zip_code).condition['temp']
end
puts weather(ARGV[0])
The shebang (#!/usr/bin/ruby) tells the kernel which interpreter to run. Save the file as weather, with no .rb extension. Then, in the shell (do not type the $):
$ chmod a+x weather
$ ./weather [ZIPCODE]
After it works, symlink it into /usr/local/bin so the name is on PATH. The link target must be the full path of weather, or this command must be run from the directory that contains it:
$ sudo ln -s weather /usr/local/bin/weather
Now weather can be called on the command line no matter the directory you are in.