阅读量:125
Ruby 目录操作有很多技巧,以下是一些常用的方法和技巧:
- 使用
Dir类来遍历目录:
Dir.glob("path/to/directory/*") do |file|
puts file
end
- 使用
Dir.entries方法获取目录中的所有文件和子目录:
entries = Dir.entries("path/to/directory")
puts entries
- 使用
Dir.mkdir创建目录:
Dir.mkdir("path/to/directory") unless Dir.exist?("path/to/directory")
- 使用
Dir.makedirs创建多级目录:
Dir.makedirs("path/to/directory/subdirectory") unless Dir.exist?("path/to/directory/subdirectory")
- 使用
Dir.rmdir删除目录:
Dir.rmdir("path/to/directory") if Dir.empty?("path/to/directory")
- 使用
Dir.rmdir删除空目录及其内容:
Dir.rmdir("path/to/directory", recursive: true) if Dir.empty?("path/to/directory")
- 使用
File.join和File.dirname拼接和获取目录路径:
directory = File.dirname("path/to/directory")
filename = "file.txt"
full_path = File.join(directory, filename)
puts full_path
- 使用
File.exist?检查文件或目录是否存在:
if File.exist?("path/to/file")
puts "File exists"
else
puts "File does not exist"
end
- 使用
File.directory?检查给定的路径是否是目录:
if File.directory?("path/to/directory")
puts "It's a directory"
else
puts "It's not a directory"
end
- 使用
File.file?检查给定的路径是否是文件:
if File.file?("path/to/file")
puts "It's a file"
else
puts "It's not a file"
end
- 使用
File.read读取文件内容:
content = File.read("path/to/file")
puts content
- 使用
File.write写入文件内容:
File.write("path/to/file", "This is the content.")
这些技巧可以帮助你在 Ruby 中更有效地操作目录。