Search code examples
rubypathpathname

How to change a file's path within ruby


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}"))}

Solution

  • 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}"