From: William James Date: 2006-12-31T05:40:18+09:00 Subject: Re: Newbie: It works, how can I make it better? Jay Bornhoft wrote: > I wrote this little prog giving the user two choices. > > I would really appreciate any advice on how I can improve anything about > this program (structure, layout, etc) > > Many thanks! > > Code: > ----- > # Name: 2choices-jb.rb > # Date: December 2006 > # Author: Jason Bornhoft > # Email: jbornhoft@gmail.com > > puts "" > puts "Conversion Program" > puts "------------------\n" > > puts "Would you like to convert:" > puts "1. F to C" > puts "2. C to F" > puts"Enter your choice now: " > choice = gets.chomp.to_i > > if choice == 1 > puts "Enter a temperature in F:" > fahr = gets.chomp.to_f > cent = ( (fahr - 32) / 1.8 ) > puts fahr.to_s + " F is " + cent.round.to_s + " C." > > elsif choice == 2 > puts "Enter a temperature in C:" > cent = gets.chomp.to_f > fahr = ( (cent * 1.8) + 32 ) > puts cent.to_s + " C is " + fahr.round.to_s + " F." > else > puts "That is a not a valid choice. Good bye!" > end print " Conversion Program ------------------ Would you like to convert: 1. F to C 2. C to F Enter your choice now: " case gets.to_i when 1 print "Enter a temperature in F: " fahr = gets.to_f cent = ( (fahr - 32) / 1.8 ) puts fahr.to_s + " F is " + cent.round.to_s + " C." when 2 print "Enter a temperature in C: " cent = gets.to_f fahr = ( (cent * 1.8) + 32 ) puts "#{ cent } C is #{ fahr.round } F." else puts "That is a not a valid choice. Good bye!" end --- A more interesting way. ----- print " Conversion Program ------------------ Would you like to convert: 1. F to C 2. C to F Enter your choice now: " def convert( from, to, func ) print "Enter a temperature in #{from}: " temp = gets.to_f puts "#{temp} #{from} is #{func[temp].round} #{to}." end case gets.to_i when 1 convert( "F", "C", proc{|f| (f - 32) / 1.8 } ) when 2 convert( "C", "F", proc{|f| f * 1.8 + 32 } ) else puts "That is a not a valid choice. Good bye!" end