Programming Fundamentals/Files/Ruby

From Wikiversity
Jump to navigation Jump to search

files.rb[edit | edit source]

# This program creates a file, adds data to the file, displays the file,
# appends more data to the file, displays the file, and then deletes the file.
# It will not run if the file already exists.
#
# References:
#     https://www.mathsisfun.com/temperature-conversion.html
#     https://en.wikibooks.org/wiki/Ruby_Programming

def create_file(filename)
    file = File.new(filename, "w")
    file.puts("C\tF")
    for c in (0..50).step(1)
        f = c * 9.0 / 5.0 + 32
        file.puts (c).to_s + "\t" + (f).to_s
    end
    file.close
end

def read_file(filename)
    file = File.open(filename, "r")
    while not file.eof
        line = file.gets
        puts(line)
    end
    file.close
    puts("")
end

def append_file(filename)
    file = File.open(filename, "a")
    for c in (51..100).step(1)
        f = c * 9.0 / 5.0 + 32
        file.puts (c).to_s + "\t" + (f).to_s
    end
    file.close
end

def delete_file(filename)
    File.delete(filename)
end

def main()
    filename = "~file.txt"

    if File.exist?(filename)
        print("File already exists.")
    else
        create_file(filename)
        read_file(filename)
        append_file(filename)
        read_file(filename)
        delete_file(filename)
    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]