Challenge 18: Temperature Converter

Temperature conversion, like volume or any other unit conversion is typically a trivial, but necessary calculation that we have to do on a daily or weekly basis. This challenge asks the developer to write a program that asks the user what temperature they’re converting to, and what the recorded temperature is, and then spit out a number in the converted units. As part of the expansion, it suggests incorporating Kelvin into the conversion choices.

This is an interesting addition to the challenge, as it requires the dev to figure out how to write a method that scales in a reasonable way. For example: with Celsius and Fahrenheit (I always had to look up how to spell that up until completing this challenge) there are only two ways the conversion can go: 

  1. F => C
  2. C => F. 

If you add in Kelvin, those two conversions become:

  1. F => C
  2. F => K
  3. C => F
  4. C => K
  5. K => F
  6. K => C

As it stands, I can’t actually think of another temperature measurement unit, and I can’t be bothered to look it up, so I’m just going to stick with these three units. The basic version was pretty easy, but getting into three units was interesting. I didn’t want to do an if/else statement for all six, so I wound up breaking it down into ternary chunks:

def convertTempUnits(unit_to,unit_from,measurement)

   if unit_to == “C”

       celsius = unit_from == “F” ? (measurement – 32) * 5/9 : celsius = measurement – 273.15

   elsif unit_to == “F”

       fahrenheit = unit_from == “C” ? (measurement * 9/5) + 32 : ((measurement – 273.15) * 9/5) + 32

   elsif unit_to == “K”

       kelvin = unit_from == “F” ? ((measurement – 32) * 5/9) + 273.15 : measurement + 273.15

   end

end

The other fun part is that I didn’t want the user to be able to choose the same unit both times, so I passed in an argument that subtracts from the array in the chooseOne(prompt,choicesArray) option list, and it returns the updated, slightly limited array:

unit_from = chooseOne(“Pick the unit you wish to convert from”,[“C”,”F”,”K”])

unit_to = chooseOne(“Pick the unit you wish to convert to”,[“C”,”F”,”K”]-[unit_from])In the end, I’m satisfied with the way this challenge came out, but I’m interested in how to more effectively scale up from just three units. I think one way to do that might be to reduce the problem down to some easier problem, like have a default convertbetweenCelsiusAndFahrenheit() method, and then filter through what the starting and ending conversions are, and then I could just call that method. Anyway, that’s Day 14 of 57!

Published by corbettbw

I am a Ruby developer in Phoenix, AZ. I'm interested in the intersection of technology and social justice, love weird science facts, and my dog, Coco; a cute black lab/pit bull mix, who won't stop eating rocks.

Leave a comment