From: Sander Land Date: 2006-10-06T06:31:48+09:00 Subject: Re: 1st program -- how would you improve this? On 10/5/06, 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 > ... > Works .. but it's not pretty, at least in terms of lack of methods > etc. Other ways to improve this? Hi Esmail, Here's my shot at rewriting your program. Note that this is simply how I would write it, not everything changed is necessarily an 'improvement'. require 'open-uri' def random_date(years_back=5) Time.at(Time.now - rand(years_back * 365 * 24 * 3600)).strftime('%y%m%d') end r_date=random_date(10) puts r_date open("http://antwrp.gsfc.nasa.gov/apod/ap#{r_date}.html") {|f| text = f.read if text =~ /([^<]*)/i puts "----------------------------------------------" puts $1.strip puts "----------------------------------------------\n\n" end if text =~ /href=\"([^\"]+(jpg|gif))\">/i image = $1 fetch_url = "http://apod.nasa.gov/apod/" + image puts fetch_url # system(...) end } Comments: - your random_date generated invalid dates sometimes, 01/30/02 and such. Using timestamps for everything is a bit more stable (Although slightly off if lots of leap years are in the range). - puts does to_s automatically, so printf("%s\n",..) is never needed - reading the text per line was meant as an optimization? This is probably not necessary. - $' / $` and such are rarely used in Ruby, try to avoid them when the more readable $1 or String#scan will do. - more methods / classes are not really needed for such a small program.