What would be a safe and efficient way to delete all files in a directory in pure Ruby? I wrote
Dir.foreach(dir_path) {|f| File.delete(f) if f != '.' && f != '..'}
but it gives me a No such file or directory error.
Thank you.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You’re probably getting that error because your current working directory doesn’t match
dir_path—File.delete(f)is being given just the filename for a file indir_path. (I hope you didn’t have any important files in the current working directory with same names in thedir_pathdirectory.)You need to use
File.join(dir_path, f)to construct the filename you wish to delete. You also need to figure out how you want to handle directories: