0

I have compiled the user's answers into a .TXT file and move it to another location, where I would store all the answers. I would need that .TXT to be named differently each time a user runs the application, so that the file is not replaced. I thought about appending time stamps next to the original name, but not sure how to do that.

My code:

require 'FileUtils'

puts "1) How would you rate the manual? Range: 1-10."
rating_range = gets.to_i

puts "2) How could the manual be improved? Type your answer below:"
improvement = gets.chomp

puts "3) What would you add to the manual. Type your answer below:"
addition = gets.chomp

puts "4) Indicate any general comments you would like to add:"
general_comments = gets.chomp


File.open("Survey.txt", 'w') { |file| 
file << "1) #{rating_range}\n"
file << "2) #{improvement}\n"
file << "3) #{addition}\n"
file << "4) #{general_comments}\n"
}   
FileUtils.mv('/Documents/Survey.txt', '/Stuff')

The file Survey.txt should be named differently each time. Any ideas?

3 Answers 3

2

Time.now http://ruby-doc.org/core-2.2.0/Time.html

filename = "Survey-#{Time.now}"
File.open(filename, 'w')
FileUtils.mv(filename, '/Stuff')
1

Timestamps aren't really guaranteed to be unique. Although it's unlikely you'd get exact duplicates, it's still possible. If you're looking for a file solution, you can use a UUID:

require 'securerandom'
uuid =  SecureRandom.uuid
File.open("Survey-#{uuid}.txt", 'w') { |file| 
  ...
}

Of course for a more robust solution, you should be using a database. :)

4
  • Thanks. I got a false appended to the name of the file. What am I doing wrongly?
    – Topa_14
    Apr 11, 2016 at 23:29
  • Oops. I had a mistake in my code. I had the require on the uuid line when I should have had the call to SecureRandom.uuid. I edited the answer.
    – djsumdog
    Apr 12, 2016 at 1:21
  • Thanks, It works perfectly now. What I can't do now is compile the code with ocra. I use this command, as usual: ocra *.rb. The compilation starts and fnishes without errors, but the executable is not generated. Any ideas?
    – Topa_14
    Apr 12, 2016 at 13:59
  • If you're have trouble with orca, I'd start a new question. Be sure to include your error output.
    – djsumdog
    Apr 12, 2016 at 14:46
0

Try replacing

File.open("Survey.txt", 'w') { |file| 

with

File.open("Survey_" + Time.now.to_i.to_s + ".txt", 'w') { |file|

This will append the time in seconds since the unix epoch to the filename. If you just use Time.now you'll end up with characters like colons in the filename, which could be problematic depending on your filesystem.

Do you just want to differentiate files, or does the timestamp need to be readable?

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.