Topa_14
Topa_14

Reputation: 199

How to name just created .TXT files in such a way that file name differs each time

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?

Upvotes: 0

Views: 51

Answers (3)

djsumdog
djsumdog

Reputation: 2710

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. :)

Upvotes: 1

ma489
ma489

Reputation: 11

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?

Upvotes: 0

Schylar
Schylar

Reputation: 774

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

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

Upvotes: 2

Related Questions