问题
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 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)
;-)
来源:https://stackoverflow.com/questions/18776399/simple-ruby-input-and-output-exercise-log