質問

I'm trying to move files from one folder to another via Ruby, but I'm stuck trying to get Pathname.new to work. For reference the files are being held in array as an inbetween from their normal dir. I know I could move it via CLI but I'd like the program to do it for me. This is what I have so far. I know it's wrong; I just don't get how to fix it.

temp_array.each {|song| song.path(Pathname.new("/Users/tsiege/Desktop/#{playlist_name}"))}
役に立ちましたか?

解決

Have a look at FileUtils.mv:

require 'fileutils'

temp_array.each do |song|
  FileUtils.mv song.path, "/Users/tsiege/Desktop/#{playlist_name}"
end

Be sure that the directory #{playlist_name} exists before you do, though:

FileUtils.mkdir_p "/Users/tsiege/Desktop/#{playlist_name}"

他のヒント

To move files you can use FileUtils.mv:

require 'fileutils'
FileUtils.mv 'from.ext', 'to.ext'

http://ruby-doc.org/stdlib-1.9.3/libdoc/fileutils/rdoc/FileUtils.html#method-c-mv

And if you want a list of files in a directory you can use:

Dir['/path/to/dir/*']    

http://ruby-doc.org/core-1.9.3/Dir.html

Lastly, you may also want to check if you have a file or directory:

File.file? file
File.directory? dir

http://ruby-doc.org/core-1.9.3/File.html#method-c-file-3F

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top