How to Copy File in Ruby: Simple Syntax and Example
In Ruby, you can copy a file using the
FileUtils.cp method from the fileutils module. This method takes the source file path and the destination file path as arguments and copies the file content.Syntax
The basic syntax to copy a file in Ruby uses the FileUtils.cp method. You need to require the fileutils module first. The method takes two arguments: the source file path and the destination file path.
- require 'fileutils': Loads the FileUtils module.
- FileUtils.cp(source, destination): Copies the file from
sourcetodestination.
ruby
require 'fileutils' FileUtils.cp('source.txt', 'destination.txt')
Example
This example shows how to copy a file named example.txt to a new file named copy_example.txt. It demonstrates the full process including requiring the module and calling the copy method.
ruby
require 'fileutils' # Create a sample file File.write('example.txt', 'Hello, Ruby file copy!') # Copy the file FileUtils.cp('example.txt', 'copy_example.txt') # Read and print the copied file content puts File.read('copy_example.txt')
Output
Hello, Ruby file copy!
Common Pitfalls
Some common mistakes when copying files in Ruby include:
- Forgetting to
require 'fileutils', which causes aNameError. - Using incorrect file paths, leading to
Errno::ENOENT(file not found) errors. - Not having write permission on the destination folder, causing permission errors.
Always check that the source file exists and the destination path is writable.
ruby
# Wrong: forgetting to require fileutils # FileUtils.cp('source.txt', 'dest.txt') # NameError # Correct way: require 'fileutils' FileUtils.cp('source.txt', 'dest.txt')
Quick Reference
Here is a quick summary of the FileUtils.cp method:
| Method | Description |
|---|---|
| FileUtils.cp(source, destination) | Copies a file from source path to destination path. |
| FileUtils.cp_r(source, destination) | Copies directories recursively. |
| require 'fileutils' | Loads the FileUtils module needed for file operations. |
Key Takeaways
Use FileUtils.cp to copy files in Ruby after requiring 'fileutils'.
Always provide correct source and destination file paths.
Check file permissions to avoid errors during copying.
FileUtils.cp copies single files; use FileUtils.cp_r for directories.
Forgetting to require 'fileutils' causes errors.