From: Timothy Goddard Date: 2006-10-06T07:05:04+09:00 Subject: Re: 1st program -- how would you improve this? Esmail Bonakdarian wrote: > Hi, > > I just wrote my first Ruby program and I would be very interested in > some feedback as to style and how to write things more in the > Ruby-way. > > I know I could use more methods and/or possibly classes, and that > will happen, but for now I would like to hear what betrays my > programming style coming from other languages. > > Thanks, > Esmail > > > > Briefly, this tiny program grabs a HTML for a random date within the > last 10 years from the Astro Picture of the Day (APOD) site > (http://antwrp.gsfc.nasa.gov/apod/archivepix.html). > > It then parses the HTML file to extract the name of the larger .jpg or > .gif file (there is usually a smaller version too), generates the > correct URL for the image, and then fires up eog (a Linux program to > display images) to fetch and display the image. > > Works .. but it's not pretty, at least in terms of lack of methods > etc. Other ways to improve this? > <> You could use Hpricot to do this much more easily and reliably. I've whipped up an example of using it for this. Note also that your random dat function could produce a date in the future up to the end of the current year. Error checking when using any of the network libraries is also a must. For a first program that's pretty good though! You obviously have the hang of using Ruby, you just need to pick up on a few of the libraries out there and how best to use them. Here's how I would do it: # Remove the rubygems require if you manually installed hpricot require 'rubygems' require 'hpricot' require 'net/http' class Time def self.random(years_back = 10) # Set start and end times end_time = Time.now start_time = Time.mktime(end_time.year - 10, end_time.month, end_time.day, 0, 0,0,0) Time.at(start_time + rand(end_time - start_time)) end end # Select a date r_date = Time.random.strftime("%y%m%d") puts r_date # Retrieve the page response = Net::HTTP.get_response("antwrp.gsfc.nasa.gov", "/apod/ap#{r_date}.html") unless (200..299) === response.code.to_i puts "There was an error retrieving the document" puts "Response code: #{response.code}" exit end # Parse the document doc = Hpricot(response.body) # Extract title title = (doc / "title").first.inner_html puts "Title: #{title}" # Extact all images images = (doc/"img") if images.length == 0 puts "Could not extract the image from the document." exit end # Assume the first image is the one we want. image = images.first["src"] puts "Running eog (whatever that is) to load image #{image}." # Execute the program. Note that it depends on the image path being relative. system("eog http://apod.nasa.gov/apod/#{image}")