I'd like to delete a directory that may or may not contain files or other directories. Looking in the Ruby docs I found Dir.rmdir but it won't delete non-empty dir. Is there a convenience method that let's me do this? Or do I need to write a recursive method to examine everything below the directory?
Removing a directory tree is also straightforward and simple with FileUtils. remove_dir , which recursively deletes the contents of a directory. This method ignores StandardError if force(second parameter) is true. Ruby provides several methods for removing directories, but mostly we use remove_dir.
To remove a directory and all its contents, including any subdirectories and files, use the rm command with the recursive option, -r . Directories that are removed with the rmdir command cannot be recovered, nor can directories and their contents removed with the rm -r command.
Using Ruby's Mkdir Method To Create A New Directory If you want to create a new folder with Ruby you can use the Dir. mkdir method. If given a relative path, this directory is created under the current path ( Dir. pwd ).
require 'fileutils' FileUtils.rm_rf(dir)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With