Skip to content

Instantly share code, notes, and snippets.

Created August 13, 2016 22:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/6ea4432a66cb782264a228b972e756b2 to your computer and use it in GitHub Desktop.
Save anonymous/6ea4432a66cb782264a228b972e756b2 to your computer and use it in GitHub Desktop.
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
# 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