Created
October 26, 2010 17:35
-
-
Save samnang/647369 to your computer and use it in GitHub Desktop.
Temperature Converter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'temperature_converter' | |
#================= Program ==================# | |
print %Q{ | |
Welcome to super simple temperature converter | |
============================================= | |
1. Celsius to Fahrenheit | |
2. Fahrenheit to Celsius | |
Please select our converter method[1]:} | |
method_number = gets.chop | |
STDOUT.flush | |
method_number = method_number.empty? ? "1" : method_number | |
print "Please input the value to be converted:" | |
from_value = gets.chop | |
STDOUT.flush | |
TemperatureConverter.convert(method_number, from_value.to_f) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TemperatureConverter | |
METHODS = { | |
"1" => { :name => "Celsius to Fahrenheit", | |
:formula => lambda { |value| value * 9/5.0 + 32 }, | |
:absolute_zero => -273.15 | |
}, | |
"2" => { :name => "Fahrenheit to Celsius", | |
:formula => lambda { |value| (value - 32) * 5/9.0 }, | |
:absolute_zero => -459.67 | |
} | |
} | |
def self.convert(method_number , from_value) | |
method = METHODS[method_number] | |
raise StandardError.new("Invalid value") if from_value < method[:absolute_zero] | |
result = method[:formula].call from_value | |
print_output(method, from_value, result) | |
result | |
end | |
def self.print_output(method, from_value, result_value) | |
from, result = method[:name].split("to") | |
puts "Convet from %s= %.2f => %s= %.2f" % [from, from_value, result, result_value] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment