Jump to content

Programming Fundamentals/Arrays/Ruby

From Wikiversity

arrays.rb

[edit | edit source]
# This program uses arrays to display temperature conversion tables 
# and temperature as an array subscript to find a given conversion.
#
# References:
#     https://www.mathsisfun.com/temperature-conversion.html
#     https://en.wikibooks.org/wiki/Ruby_Programming

def build_c(size)
    c = Array.new(size)
    for index in (0..size)
        value = index * 9.0 / 5 + 32
        c[index] = value
    end
    return c
end

def build_f(size)
    f = Array.new(size)
    for index in (0..size)
        value = (index - 32) * 5.0 / 9
        f[index] = value
    end
    return f
end

def display_array(name, array)
    for index in (0..array.size - 1)
        puts name + "[" + (index).to_s + "] = " + (array[index]).to_s
    end
end

def find_temperature(c, f)
    size = minimum(c.length, f.length)
    begin
        puts "Enter a temperature between 0 and " + ((size - 1)).to_s
        temp = gets.chomp.to_i
    end while (temp < 0 || temp > size - 1)
    puts (temp).to_s + "° Celsius is " + (c[temp]).to_s + "° Fahrenheit"
    puts (temp).to_s + "° Fahrenheit is " + (f[temp]).to_s + "° Celsius"
end

def minimum(value1, value2)
    if value1 < value2
        result = value1
    else
        result = value2
    end
        
    return result
end

def main()
    c = build_c(100)
    f = build_f(212)
    display_array("C", c)
    display_array("F", f)
    find_temperature(c, f)
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]