简单的 Ruby 输入输出练习日志 [英] simple Ruby Input and Output Exercise log

查看:48
本文介绍了简单的 Ruby 输入输出练习日志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的编程课上有一个项目.这是我的作业:创建一个程序,允许用户输入他们今天锻炼了多少小时.然后程序应该输出他们一直锻炼的总小时数.为了让程序在第一次运行后继续运行,需要从文件中写入和检索总练习时间.

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.

这是我目前的代码:

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

我还需要添加什么?

推荐答案

这个怎么样?

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)

;-)

这篇关于简单的 Ruby 输入输出练习日志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆