0

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
3
  • Start with the initial work. Suppose you don't need to read / write to a file. For instance, pretend that the project assignment is simply to take an input (prompting for # hours worked out) and then output it. Can you show us code for that? Commented Sep 12, 2013 at 21:26
  • Once you have that, I would recommend a good link like: stackoverflow.com/questions/2437326/… Commented Sep 12, 2013 at 21:28
  • friend of yours working on the same thing? stackoverflow.com/questions/18776399/… ;-) Commented Sep 13, 2013 at 2:02

1 Answer 1

0

Write your code like:

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

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

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.

Sign up to request clarification or add additional context in comments.

2 Comments

what is the |fi| for?
You'll need to figure that out. It's all documented in books, plus Ruby's online documentation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.