Sunday, July 26, 2009
Getting bored one fine weekend, I decided to start learning Ruby, a scripting language. My impressions of Ruby thus far have all been positive - it is much more fun to code in than C or Actionscript. Here is a simple example program I just coded learning Ruby, and while it might not be of the highest quality I hope it'll be of some help to someone out there.
#Heat Index Calculator in Celsius
#Formula from Wikipedia (http://en.wikipedia.org/wiki/Heat_index)
#Formula for approximating the heat index in degrees Fahrenheit is accurate to within ±1.3 °F.
#It is useful only when the temperature is at least 80 °F (26.6°C) and the relative humidity is at least 40%.
puts 'Temperature(C) (space) relative humidity(%)'
#Clears the buffer in prepration for input
STDOUT.flush
#Gets input, removes spaces '.split(/ /)' and then converts each element to a float 'map{|x| x.to_f}' - x being the elements and 'x.to_f' the operation to carry out on each element
tc,r = gets.split(/ /).map {|x| x.to_f}
#°C to °F Multiply by 9, divide by 5, then add 32
tf = tc * 9 / 5 + 32
#Constants used
C1 = -42.379
C2 = 2.04901523
C3 = 10.14333127
C4 = -0.22475541
C5 = -6.83783 * 10**-3
C6 = -5.481717 * 10**-2
C7 = 1.22874 * 10**-3
C8 = 8.5282 * 10**-4
C9 = -1.99 * 10**-6
#Applying the heat index formula
hif = C1 + C2 * tf + C3 * r + C4 * tf * r + C5 * tf**2 + C6 * r**2 + C7 * tf**2 * r + C8 * tf * r**2 + C9 * tf**2 * r**2
#°F to °C
hic = (hif - 32) * 5 / 9
#Displays heat index to 5 significant figures, converts it into a string so that 'C' can be appended
puts hic.to_s[0..4] + ' C'
Labels: code, heat index, programming, ruby, SINGAPORE IS HOT
