Creating a Simple Temperature Converter in Ruby

Having a program that you can use to convert temperatures on the fly can be very handy. In this article we’ll be discussing how to create reusable methods that convert temperatures between Celsius and Fahrenheit and showing off how to implement them in a small program.

Defining the Methods

When creating the converter the first thing you should do is define the two methods that’ll convert from Celsius to Fahrenheit and vice versa.

Both of these methods are very simple, taking only one argument which is the temperature to convert. Each method is just a single line and returns the conversion.

def celfar(temp) # F = (C * 9 / 5)  + 32
return (temp * 9 / 5) + 32
end

def farcel(temp) # C = (F - 32) * 5 / 9
return (temp - 32) * 5 / 9
end

These methods can be used to convert temperatures and can be easily copy pasted into any other program where you might need them.

Getting the Input

First you need to insert a short sentence asking the user which scale they’re converting from and use “gets.chomp()” to get their response.

puts "Are you converting from Celsius or Fahrenheit?"
choice = gets.chomp()

After that it’s time to get the number the user wants to convert. To do this use “gets.to_i” instead of “gets.chomp()”. The “.to_i” method converts the user’s input from a string to an integer so that it can be used in calculations.

puts "Please enter a temperature"
num = gets.to_i

Finally you need to set up an if statement which will carry out the corresponding conversion based on which scale the user picked earlier. Inside the statement pass “num” into the appropriate method and display the end result to the user.

if choice == "Celsius"
  puts "#{num} Degrees Celsius is Equal to #{celfar(num)} Degrees Fahrenheit"
elsif choice == "Fahrenheit"
  puts "#{num} Degrees Fahrenheit is Equal to #{farcel(num)} Degrees Celsius"
end

Now the program is finished and ready to run.

Final Suggestions

To make the program more fully fleshed out you could insert new methods that convert to Kelvin as well. You could also try moving the program beyond the command line and creating a UI for it.

Good Luck!

Download the above source code here.

If you have any comments or questions email them to me at nick@crumbsofcode.com