simple Ruby Input and Output Exercise log [duplicate]

自古美人都是妖i 提交于 2019-12-11 23:42:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!