user3927287
user3927287

Reputation: 303

Moving files to a directory created on the fly

I'm looking to move certain .txt files from one directory to another, that I'm creating on the fly containing version numbers and date/time stored as variables:

require 'fileutils'
version = '2.1.6.0'
time = Time.now.strftime("%Y%m%d%H%M%S")
dir = FileUtils.makedirs ("ruby/bar/#{version}/#{time}")

FileUtils.mv 'foo.txt', dir

The directory is created successfully, however a no implicit conversion of Array into String error is returned for the moving file part.

I tried to modify the code by adding:

dir = dir.to_s

but No such file or directory - (timings.txt, ["ruby/bar/2.1.6.0/20141007183424"]) is returned.

Do I need to convert it to a string? Or is not even possible to move a file to a path saved as a variable?

Upvotes: 0

Views: 1329

Answers (1)

Marc Plano-Lesay
Marc Plano-Lesay

Reputation: 6958

You could save the directory name to a variable, then reuse it:

require 'fileutils'
version = '2.1.6.0'
time = Time.now.strftime("%Y%m%d%H%M%S")
dirname = "ruby/bar/#{version}/#{time}"
FileUtils.makedirs dirname

FileUtils.mv 'foo.txt', dirname

FileUtils.makedirs returns the array containing paths to the folder it created. It's an array because you can call it with multiple folders to create:

FileUtils.makedir ["foo", "bar"]

If you want to reuse the FileUtils.makedirs result, you'll have to do something like this:

require 'fileutils'
version = '2.1.6.0'
time = Time.now.strftime("%Y%m%d%H%M%S")
dir = FileUtils.makedirs "ruby/bar/#{version}/#{time}"

FileUtils.mv 'foo.txt', dir.first

Upvotes: 4

Related Questions