Jump to content

Programming Fundamentals/Conditions/Ruby

From Wikiversity

conditions.rb

[edit | edit source]
# This program asks the user to select Fahrenheit or Celsius conversion
# and input a given temperature. Then the program converts the given 
# temperature and displays the result.
#
# References:
#     https://www.mathsisfun.com/temperature-conversion.html
#     https://en.wikibooks.org/wiki/Ruby_Programming

def get_choice()
    puts "Enter F to convert to Fahrenheit or C to convert to Celsius:"
    choice = gets.chomp
    return choice
end

def get_temperature(label)
    puts "Enter " + label + " temperature:"
    temperature = gets.chomp.to_f
    return temperature
end

def calculate_celsius(fahrenheit)
    celsius = (fahrenheit - 32) * 5 / 9
    return celsius
end

def calculate_fahrenheit(celsius)
    fahrenheit = celsius * 9 / 5 + 32    
    return fahrenheit
end

def display_result(temperature, from, result, to)
    puts (temperature).to_s + "° " + from + " is " + (result).to_s + "° " + to
end

def main()
    # main could either be an if-else structure or a case-when structure

    choice = get_choice()

    # if-else approach
    if choice == "C" || choice == "c"
        temperature = get_temperature("Fahrenheit")
        result = calculate_celsius(temperature)
        display_result(temperature, "Fahrenheit", result, "Celsius")
    elsif choice == "F" || choice == "f"
        temperature = get_temperature("Celsius")
        result = calculate_fahrenheit(temperature)
        display_result(temperature, "Celsius", result, "Fahrenheit")
    else
        puts "You must enter C to convert to Celsius or F to convert to Fahrenheit!"
    end

    # case-when approach
    case choice
        when "C"
            temperature = get_temperature("Fahrenheit")
            result = calculate_celsius(temperature)
            display_result(temperature, "Fahrenheit", result, "Celsius")
        when "c"
            temperature = get_temperature("Fahrenheit")
            result = calculate_celsius(temperature)
            display_result(temperature, "Fahrenheit", result, "Celsius")
        when "F"
            temperature = get_temperature("Celsius")
            result = calculate_fahrenheit(temperature)
            display_result(temperature, "Celsius", result, "Fahrenheit")
        when "f"
            temperature = get_temperature("Celsius")
            result = calculate_fahrenheit(temperature)
            display_result(temperature, "Celsius", result, "Fahrenheit")
        else
            puts "You must enter C to convert to Celsius or F to convert to Fahrenheit!"
    end
end

main()

Try It

[edit | edit source]

Copy and paste the code above into one of the following free online development environments or use your own Ruby compiler / interpreter / IDE.

See Also

[edit | edit source]