We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
I was wondering why nobody was trying to use objects since this problem is well suited for them. Maybe it is becauseHackerRank forces silly interfaces like convert_temp on us.
If you allow me some criticism, I'd say you are using obejcts but not taking the opportunity to benefit from designing with them im mind. Instead of writing a single class TemperatureConverter, here is how I'd write it:
classTemperatureConverterdefinitialize(degrees)@degrees=degreesenddefvalue@degreesenddefto(a_unit)a_unit.from(self)enddefto_celsiussubclass_responsibilityenddefto_fahrenheitsubclass_responsibilityenddefto_kelvinsubclass_responsibilityenddefsubclass_responsibilityraise'Should be implemented by subclass'endendclassCelsius<TemperatureConverterdefto_celsiusselfenddefto_fahrenheitFahrenheit.new@degrees*9/5r+32enddefto_kelvinKelvin.new@degrees+273.15enddefself.from(a_temperature)a_temperature.to_celsiusendendclassFahrenheit<TemperatureConverterdefto_celsiusCelsius.new(@degrees-32)*5/9renddefto_fahrenheitselfenddefto_kelvinKelvin.new(@degrees+459.67)*5/9renddefself.from(a_temperature)a_temperature.to_fahrenheitendendclassKelvin<TemperatureConverterdefto_celsiusCelsius.new@degrees-273.15enddefto_fahrenheitFahrenheit.new@degrees*9/5r-459.67enddefto_kelvinselfenddefself.from(a_temperature)a_temperature.to_kelvinendenddefconvert_temp(degrees,input_scale:,output_scale:'celsius')Object.const_get(input_scale.capitalize).new(degrees).to(Object.const_get(output_scale.capitalize)).value# or alternatively# Object.const_get(output_scale.capitalize).from(Object.const_get(input_scale.capitalize).new(degrees)).valueend
Look ma, no ifs!
I am pretty sure my design can be improved as well, and the naming is also suspiciuous. Why is a unit like Kelvin a sublclass of TemperatureConverter? Take a look at Aconcagua (Measures) If you'd like to study some production quality code.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Ruby - Methods - Keyword Arguments
You are viewing a single comment's thread. Return to all comments →
I was wondering why nobody was trying to use objects since this problem is well suited for them. Maybe it is becauseHackerRank forces silly interfaces like
convert_temp
on us.If you allow me some criticism, I'd say you are using obejcts but not taking the opportunity to benefit from designing with them im mind. Instead of writing a single class
TemperatureConverter
, here is how I'd write it:Look ma, no ifs!
I am pretty sure my design can be improved as well, and the naming is also suspiciuous. Why is a unit like
Kelvin
a sublclass ofTemperatureConverter
? Take a look at Aconcagua (Measures) If you'd like to study some production quality code.