TheAlgorithms-Ruby/conversions/temperature_conversions.rb

73 lines
2.3 KiB
Ruby
Raw Normal View History

# A ruby program for temperature conversions
2021-04-01 03:55:38 +02:00
module TemperatureConversion
# celsius -> kelvin = value of celsius + 273.15 => K
def self.celsius_to_kelvin(celsius_input)
2021-04-01 03:49:42 +02:00
kelvin_output = (celsius_input + 273.15).round(2)
puts "#{celsius_input}°C = #{kelvin_output}K"
2021-04-01 03:55:38 +02:00
rescue
puts "Error: Please provide number only!"
end
2021-04-01 03:55:38 +02:00
# kelvin -> celsius = vale of kelvin - 273.15 => °C
def self.kelvin_to_celsius(kelvin_input)
2021-04-01 03:49:42 +02:00
celsius_output = (kelvin_input - 273.15).round(2)
puts "#{kelvin_input}K = #{celsius_output}°C"
2021-04-01 03:55:38 +02:00
rescue
puts "Error: Please provide number only!"
end
2021-04-01 03:55:38 +02:00
# celsius -> fahrenheit = (value of celsius * 9 / 5) + 32 => °F
def self.celsius_to_fahrenheit(celsius_input)
2021-04-01 03:49:42 +02:00
fahrenheit_output = ((celsius_input * 9 / 5) + 32).round(2)
puts "#{celsius_input}°C = #{fahrenheit_output}°F"
2021-04-01 03:55:38 +02:00
rescue
puts "Error: Please provide number only!"
end
2021-04-01 03:55:38 +02:00
# fahrenheit -> celsius = (value of fahrenheit - 32) * 5 / 9 => °C
def self.fahrenheit_to_celsius(fahrenheit_input)
2021-04-01 03:49:42 +02:00
celsius_output = ((fahrenheit_input - 32) * 5 / 9).round(2)
puts "#{fahrenheit_input}°F = #{celsius_output}°C"
2021-04-01 03:55:38 +02:00
rescue
puts "Error: Please provide number only!"
end
2021-04-01 03:55:38 +02:00
# fahrenheit -> kelvin = [(value of fahrenheit - 32) * 5 / 9] + 273.15 => K
def self.fahrenheit_to_kelvin(fahrenheit_input)
kelvin_output = ((fahrenheit_input - 32) * 5 / 9).round(2).round(2)
puts "#{fahrenheit_input}°F = #{kelvin_output}K"
2021-04-01 03:55:38 +02:00
rescue
puts "Error: Please provide number only!"
end
2021-04-01 03:55:38 +02:00
# kelvin -> fahrenheit = [(value of kelvin - 32) * 5 / 9] + 273.15 => K
def self.kelvin_to_fahrenheit(kelvin_input)
2021-04-01 03:49:42 +02:00
fahrenheit_output = (((kelvin_input - 273.15) * 9 / 5) + 32).round(2).round(2)
puts "#{kelvin_input}K = #{fahrenheit_output}°F"
2021-04-01 03:55:38 +02:00
rescue
puts "Error: Please provide number only!"
end
end
# celsius <-> kelvin
2021-04-01 03:55:38 +02:00
TemperatureConversion.celsius_to_kelvin(20)
TemperatureConversion.kelvin_to_celsius(20)
# Invalid input
2021-04-01 03:55:38 +02:00
TemperatureConversion.kelvin_to_celsius("a")
# celsius <-> fahrenheit
2021-04-01 03:55:38 +02:00
TemperatureConversion.celsius_to_fahrenheit(-20)
TemperatureConversion.fahrenheit_to_celsius(68)
# Invalid input
2021-04-01 03:55:38 +02:00
TemperatureConversion.celsius_to_fahrenheit("abc")
# fahrenheit <-> kelvin
2021-04-01 03:55:38 +02:00
TemperatureConversion.fahrenheit_to_kelvin(60)
TemperatureConversion.kelvin_to_fahrenheit(-60)
# Invalid input
2021-04-01 03:55:38 +02:00
TemperatureConversion.fahrenheit_to_kelvin("60")