Programming Fundamentals/Objects/Ruby

From Wikiversity
Jump to navigation Jump to search

objects.rs[edit | edit source]

# This class converts temperature between Celsius and Fahrenheit.
# It may be used by assigning a value to either Celsius or Fahrenheit 
# and then retrieving the other value, or by calling the to_celsius or
# to_fahrenheit methods directly.
#
# References:
#     https://www.mathsisfun.com/temperature-conversion.html
#     https://en.wikibooks.org/wiki/Ruby_Programming

class Temperature
    @celsius = nil
    @fahrenheit = nil
    
    def celsius()
        @celsius
    end

    def celsius=(value)
        @celsius = value.to_f
        @fahrenheit = to_fahrenheit(@celsius)
    end
    
    def fahrenheit()
        return @fahrenheit 
    end
    
    def fahrenheit=(value)
        @fahrenheit = value.to_f
        @celsius = to_celsius(@fahrenheit)
    end
    
    def initialize(celsius: nil, fahrenheit: nil)
        if celsius != nil
            @celsius = celsius.to_f
            @fahrenheit = to_fahrenheit(@celsius)
        end
        
        if fahrenheit != nil
            @fahrenheit = fahrenheit.to_f
            @celsius = to_celsius(@fahrenheit)
        end
    end
    
    def to_celsius(fahrenheit)
        return (fahrenheit - 32) * 5 / 9
    end
    
    def to_fahrenheit(celsius)
        return celsius * 9 / 5 + 32
    end
end

# This program creates instances of the Temperature class to convert Cesius 
# and Fahrenheit temperatures.
        
def main()
    temp1 = Temperature.new(celsius: 0)
    puts("temp1.celsius = " + temp1.celsius.to_s)
    puts("temp1.fahrenheit = " + temp1.fahrenheit.to_s)
    puts("")

    temp1.celsius = 100
    puts("temp1.celsius = " + temp1.celsius.to_s)
    puts("temp1.fahrenheit = " + temp1.fahrenheit.to_s)
    puts("")
    
    temp2 = Temperature.new(fahrenheit: 0)
    puts("temp2.fahrenheit = " + temp2.fahrenheit.to_s)
    puts("temp2.celsius = " + temp2.celsius.to_s)
    puts("")

    temp2.fahrenheit = 100
    puts("temp2.fahrenheit = " + temp2.fahrenheit.to_s)
    puts("temp2.celsius = " + temp2.celsius.to_s)
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]