Converting Celsius to Fahrenheit in Ruby

I'm totally new at this. I want to ask a user to "Enter degrees in Celsius: "

Then I want the response to be "The tempurature in Fahrenheit is: " I understand what gets and puts does but I wanna use "return" to have the value returned...hmm I may be asking this the wrong way. I am confused and need help.

TIA

1 answer

  • answered 2019-08-24 00:53 pr0f3ss

    I see that you are pretty new to programming, so I'm going to guide you through the bits of code and explain what they mean and how they function.

    I'm pretty sure that you are familiar with or at least heard of functions. Functions take a set of arguments, compute stuff with the arguments and return a value. Functions in programming languages are very similar to mathematical functions as you can see with this example:

    f(x) = x^2
    

    The function f takes one argument (x) and returns an output (x^2).

    Functions make our lives easier, because if we have code that is repeatedly used, we can wrap that code into a function and just use that function, instead of writing the same code over and over again. As you know, the Celsius to Fahrenheit is a simple mathematical formula:

    (c*9/5)+32
    

    where c is the degree in Celsius.

    We can define a mathematical formula f that has the argument c and returns (c*9/5)+32. It would look like this:

    f(c) = (c*9/5)+32
    

    We can now transfer this into ruby code like this and use it later when we need it:

    def convert(c)
        return (c*9/5)+32
    end
    

    With puts we can print something line per line on the screen, so let's do this:

    puts "Enter degrees in celsius: "
    

    Now we want user input. We can get this by utilizing gets.chomp and storing the value in a variable, c:

    c = gets.chomp
    

    As gets.chomp stores its result as a character sequence, otherwise known as a string, we must convert it to a decimal value. We do this by calling the method .to_i on c:

    c = c.to_i
    

    to_i stands for to_integer, so we are saying convert this string to an integer, such that we can use it later in our function.

    Now we are ready to convert c to its Fahrenheit value. We defined a function above that does that job for us, we must only call the function with our argument in it.

    f = convert(c) #pass c as a argument to the function convert and store it in f
    

    f now holds the Fahrenheit value of c. Let's print the result:

    puts "The temperature in Fahrenheit is: #{f}" 
    

    , where #{f} lets us insert the value of f into the string.

    If you want minimal code, you can group the instructions together like this:

    def convert(c)
        return (c*9/5)+32
    end
    
    puts "Enter degrees in celsius: "
    puts "The temperature in Fahrenheit is: #{convert(gets.chomp.to_i)}" 
    

    Try to understand what is done differently here and if you have any questions, you can comment down below.