Reputation: 185
I am attempting to write a method in Ruby that deletes several named files and directories. Here is my method:
def cleanup_all_files
files = ['*.bat', '*.sh', 'lib/*.jar']
directories = %w[ data archive report log ]
files.each do |f|
File.delete(files[f])
end
directories.each do |d|
FileUtils.rm_rf(directories[d])
end
end
This results in the following error:
TypeError: no implicit conversion of String into Integer
Upvotes: 0
Views: 791
Reputation: 106782
files.each do |f|
already yields the element. Therefore calling files[f]
does not make sense. But at the same time File.delete
cannot handle patterns, it expects a specific file names. Find all files matching a pattern with Dir.glob
:
def cleanup_all_files
file_patterns = ['*.bat', '*.sh', 'lib/*.jar']
directory_patterns = %w[ data archive report log ]
file_patterns.each do |p|
Dir.glob(p) { |f| File.delete(f) }
end
directory_patterns do |p|
Dir.glob(p) { |d| FileUtils.rm_rf(d) }
end
end
Upvotes: 4