简单的Ruby输入和输出练习日志

时间:2013-09-13 00:34:29

标签: ruby ruby-on-rails-3 ruby-on-rails-3.2 ruby-on-rails-3.1

我的编程课程中有一个项目。这是我的任务:创建一个程序,允许用户输入他们今天锻炼的小时数。然后程序应该输出他们一直锻炼的总时数。为了使程序能够在第一次运行之后持续存在,需要从文件中写入和检索总运动时间。

这是我到目前为止的代码:

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

我还需要添加什么?

1 个答案:

答案 0 :(得分:-1)

怎么样?

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)

- )