如何在Ruby中创建此文件输入和输出分配 [英] How do I create this File Input and Output assignment in Ruby

查看:53
本文介绍了如何在Ruby中创建此文件输入和输出分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个任务,我不确定该怎么做.想知道是否有人可以提供帮助.就是这样:

I have an assignment that I am not sure what to do. Was wondering if anyone could help. This is it:

创建一个程序,允许用户输入他们今天锻炼了多少小时.然后,程序应输出他们在所有时间中锻炼了多少小时的总和.为了使程序能够在首次运行后继续存在,总的锻炼时间需要编写并从文件中检索.

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.

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

My code is this so far:

myFileObject2 = File.open("exercise.txt")
myFileObjecit2.read

puts "This is an exercise log. It keeps track of the number hours of exercise."

hours = gets.to_f

myFileObject2.close

推荐答案

将代码编写为:

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."

  hours = gets.chomp.to_f

end

Ruby的File.open占用一个块.当该块退出时,文件将自动关闭文件.除非您绝对肯定,否则不要使用无障碍表格.

Ruby's File.open takes a block. When that block exits File will automatically close the file. Don't use the non-block form unless you are absolutely positive you know why you should do it another way.

chomp您从gets获得的值.这是因为gets在看到尾随的END-OF-LINE之前不会返回,在Mac OS和* nix上通常为"\ n",在Windows上通常为"\ r \ n".未能使用chomp删除它的原因是无意识的开发人员大量哭泣和咬牙切齿的原因.

chomp the value you get from gets. This is because gets won't return until it sees a trailing END-OF-LINE, which is usually a "\n" on Mac OS and *nix, or "\r\n" on Windows. Failing to remove that with chomp is the cause of much weeping and gnashing of teeth in unaware developers.

程序的其余部分留给您找出.

The rest of the program is left for you to figure out.

如果"exercise.txt"尚不存在,则代码将失败.您需要弄清楚如何处理.

The code will fail if "exercise.txt" doesn't already exist. You need to figure out how to deal with that.

使用read是不好的形式,除非您绝对肯定该文件将始终位于内存中,因为将立即读取整个文件.一旦存储在内存中,它将是一大串数据,因此您必须弄清楚如何将其分解为数组,以便可以对其进行迭代.有比read更好的处理阅读方法,因此我将研究IO类,并阅读在Stack Overflow上可以找到的内容.提示:不要拖拽您的文件.

Using read is bad form unless you are absolutely positive the file will always fit in memory because the entire file will be read at once. Once it is in memory, it will be one big string of data so you'll have to figure out how to break it into an array so you can iterate it. There are better ways to handle reading than read so I'd study the IO class, plus read what you can find on Stack Overflow. Hint: Don't slurp your files.

这篇关于如何在Ruby中创建此文件输入和输出分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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