How do I move a file with Ruby?

RubyFile

Ruby Problem Overview


I want to move a file with Ruby. How do I do that?

Ruby Solutions


Solution 1 - Ruby

You can use FileUtils to do this.

#!/usr/bin/env ruby

require 'fileutils'

FileUtils.mv('/tmp/your_file', '/opt/new/location/your_file')

Remember; if you are moving across partitions, "mv" will copy the file to new destination and unlink the source path.

Solution 2 - Ruby

An old question, i'm surprised no one answered this simple solution. You don't need fileutils or a systemcall, just rename the file to the new location.

File.rename source_path, target_path

Happy coding

Solution 3 - Ruby

FileUtils.move

require 'fileutils'
FileUtils.move 'stuff.rb', '/notexist/lib/ruby'

Solution 4 - Ruby

Solution 5 - Ruby

here is a template .

 src_dir = "/full_path/to_some/ex_file.txt"

 dst_dir = "/full_path/target_dir"

 #Use the method below to do the moving
 move_src_to_target_dir(src_dir, dst_dir)



 def archive_src_to_dst_dir(src_dir, dst_dir)

     if File.exist ? (src_dir)
   
     puts "about to move this file:  #{src_dir}"

     FileUtils.mv(src_dir, dst_dir)
 else

     puts "can not find source file to move"

 end
 end

Solution 6 - Ruby

you can move your file like this

Rails.root.join('foo','bar')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionŽeljko FilipinView Question on Stackoverflow
Solution 1 - RubyBerk D. DemirView Answer on Stackoverflow
Solution 2 - RubypeterView Answer on Stackoverflow
Solution 3 - RubyŽeljko FilipinView Answer on Stackoverflow
Solution 4 - Rubyuser49221View Answer on Stackoverflow
Solution 5 - Rubyz atefView Answer on Stackoverflow
Solution 6 - RubykajalView Answer on Stackoverflow