copy a directory in ruby

To copy a directory in Ruby, you can use the FileUtils.cp_r method provided by the FileUtils module. This method allows you to recursively copy a directory and its contents. Here's an example:

main.rb
require 'fileutils'

# Copy the directory 'source_dir' to 'destination_dir'
FileUtils.cp_r('source_dir', 'destination_dir')
124 chars
5 lines

This will copy the directory source_dir to destination_dir, including all subdirectories and files. If the destination_dir directory does not exist, it will be created.

You can also use the FileUtils.cp method to copy a single file:

main.rb
require 'fileutils'

# Copy the file 'source_file' to 'destination_file'
FileUtils.cp('source_file', 'destination_file')
121 chars
5 lines

Note that both FileUtils.cp_r and FileUtils.cp methods will replace any existing files or directories with the same name in the destination directory. If you want to avoid this, you can use the FileUtils.cp_r method with a preserve option:

main.rb
require 'fileutils'

# Copy the directory 'source_dir' to 'destination_dir',
# preserving files that already exist in destination_dir
FileUtils.cp_r('source_dir', 'destination_dir', :preserve => true)
201 chars
6 lines

gistlibby LogSnag