0

I have a project in my programming class. This is my assignment: Create a program that allows the user to input how many hours they exercised for today. Then the program should output the total of how many hours they have exercised for all time. To allow the program to persist beyond the first run the total exercise time will need to be written and retrieved from a file.

This is the code I have so far:

File.open("exercise.txt", "r") do |fi|
file_content = fi.read

puts "This is an exercise log. It keeps track of the number hours of exercise. Please enter the number of hours you exercised."
hours = gets.chomp.to_f
end

output = File.open( "exercise.txt", "w" )
output << hours
output.close      
end

What else do I have to add in it?

1
  • How about creating methods get_total_to_date and save_total_to_date(total)? Since the file name will not change and you reference it more than once, best to make it a constant. Note that the file will not exist the first time you invoke get_total_to_date. Commented Sep 13, 2013 at 0:48

1 Answer 1

-1

how about this?

FILE = "total_hours.txt"

# read total_hours
if File.exist?(FILE)
  total_hours = IO.read(FILE).to_f
else
  total_hours = 0
end

# ask user for new hours
puts "How many hours?"
total_hours += gets.strip.to_f

puts "Great, you have #{total_hours} hours."

# write total_hours
IO.write(FILE, total_hours)

;-)

Sign up to request clarification or add additional context in comments.

2 Comments

is this a replacement for my code?
Weren't me! Weren't me!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.