Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 66 / 68

Converting Temperature (Celsius to Fahrenheit)

In this lesson you will convert between Celsius and Fahrenheit, practising how to turn a formula straight into code. This is for anyone searching for "Ruby Celsius Fahrenheit conversion".

Celsius to Fahrenheit is "C x 9/5 + 32", and Fahrenheit to Celsius is "(F - 32) x 5/9". Unit conversion is a classic programming exercise.

The sample code turns each formula directly into code as celsius_to_fahrenheit and fahrenheit_to_celsius. Notice how writing 9.0 explicitly as a decimal avoids the error that integer division would introduce.

A common stumbling block for beginners is integer division truncating the fractional part. In Ruby 9 / 5 between two integers gives an integer, so an accurate calculation needs an explicit decimal such as 9.0.

It is a classic conversion exercise: simple formulas turned straight into code, with good practice at keeping types in mind. The same pattern applies to plenty of other unit conversions, such as length and weight.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)