Programming Fundamentals/Conditions/Ruby: Difference between revisions

From Wikiversity
Jump to navigation Jump to search
Content deleted Content added
Creating
(No difference)

Revision as of 22:29, 3 February 2017

conditions.rs

# 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.

def to_celsius()
    puts "Enter Fahrenheit temperature:"
    f = gets.chomp.to_f
    c = (f - 32) * 5 / 9
    puts (f).to_s + "° Fahrenheit is " + (c).to_s + "° Celsius"
end

def to_fahrenheit()
    puts "Enter Celsius temperature:"
    c = gets.chomp.to_f
    f = c * 9 / 5 + 32
    puts (c).to_s + "° Celsius is " + (f).to_s + "° Fahrenheit"
end

def main()
    puts "Enter F to convert to Fahrenheit or C to convert to Celsius:"
    choice = gets.chomp
    if choice == "C" || choice == "c"
        to_celsius()
    elsif choice == "F" || choice == "f"
        to_fahrenheit()
    else
        puts "You must enter C to convert to Celsius or F to convert to Fahrenheit!"
    end
end

main()

Try It

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