Created
August 13, 2016 22:30
-
-
Save anonymous/6ea4432a66cb782264a228b972e756b2 to your computer and use it in GitHub Desktop.
This file contains 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 Temperature | |
KelvinToCelsius = 27315/100r | |
KelvinToFahrenheit = 45967/100r | |
FahrenheitFactor = 5/9r | |
def self.from_kelvin(kelvin) # could just alias | |
new(kelvin: kelvin) | |
end | |
def self.from_celsius(celsius) # IMO should be just named "celsius" | |
new(celsius: celsius) | |
end | |
def self.from_fahrenheit(fahrenheit) | |
new(fahrenheit: fahrenheit) | |
end | |
attr_reader :in_kelvin | |
def initialize(kelvin: nil, celsius: nil, fahrenheit: nil) | |
if kelvin && celsius || celsius && fahrenheit || kelvin && fahrenheit | |
raise ArgumentError, "Must only pass one of kelvin, celsius or fahrenheit" | |
elsif kelvin | |
@in_kelvin = kelvin | |
elsif celsius | |
@in_kelvin = celsius - KelvinToCelsius) | |
elsif fahrenheit | |
@in_kelvin = (fahrenheit + KelvinToFahrenheit) * FahrenheitFactor) | |
else | |
raise ArgumentError, "Must only pass at least one of kelvin, celsius or fahrenheit" | |
end | |
end | |
def in_celsius | |
@in_kelvin + KelvinToCelsius | |
end | |
def in_fahrenheit | |
(@in_kelvin / FahrenheitFactor) + KelvinToFahrenheit | |
end | |
end |
This file contains 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
# proper implementation | |
class Temperature | |
KelvinToCelsius = 27315/100r | |
KelvinToFahrenheit = 45967/100r | |
FahrenheitFactor = 5/9r | |
def self.from_kelvin(kelvin) # could just alias | |
new(kelvin) | |
end | |
def self.from_celsius(celsius) # IMO should be just named "celsius" | |
new(celsius - KelvinToCelsius) | |
end | |
def self.from_fahrenheit(fahrenheit) | |
new((fahrenheit + KelvinToFahrenheit) * FahrenheitFactor) | |
end | |
attr_reader :in_kelvin | |
def initialize(kelvin) | |
@in_kelvin = kelvin | |
end | |
def in_celsius | |
@in_kelvin + KelvinToCelsius | |
end | |
def in_fahrenheit | |
(@in_kelvin / FahrenheitFactor) + KelvinToFahrenheit | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment