Never been to TextSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

Simple Temperature Converter (See related posts)

// Temperature Converter

#
#   A simple ruby script to convert temperatures
#    Written by:  steve at r3lax.com
#

puts "Enter a temprature: "
t = gets
#regexp to make sure the entry is valid
valid = /^([\+-]?)(\d+)([CcFf]?)/
degree = valid.match(t)
#determines if you input celsius or farenheit
if (degree[3] == "c" || degree[3] == "C")
  puts "Converting from Celsius to Farenheit"
  puts "#{degree[0]} to #{((9.0/5.0) * degree[2].to_f + 32.0).to_i} F"
elsif (degree[3] == "f" || degree[3] == "F")
  puts "Converting from Farenheit to Celsius"
  puts "#{degree[0]} to #{((5.0/9.0) * (degree[2].to_f - 32.0)).to_i} C"
#Displays the usage if you didn't enter anything correctly
else 
  puts "Usage is: [+|-][C|F]"
end


You need to create an account or log in to post comments to this site.


Related Posts