通过Ruby更改目录

问题描述 投票:0回答:1

我正在尝试创建一个简单的脚本来删除我桌面上的所有文件(我使用的是Ubuntu)。

puts "Started at #{Time.now}"
Dir.chdir("/Desktop")
Dir.entries(".").each do |file|
    if file.to_s.include?("xlsx")
      puts "Deleting file #{file}" unless file == "." || file == ".."
      File.delete "#{Dir.pwd}/#{file}" unless file == "." || file == ".."
    end  
end
puts "Ended on #{Time.now}"

但是当我生成代码时,它会抛出以下错误:

chdir':没有这样的文件或目录@ dir_chdir - / Desktop(Errno :: ENOENT)

我做错了什么?

ruby linux ubuntu
1个回答
1
投票
puts "Started at #{Time.now}"
Dir.chdir("#{ENV['HOME']}/Desktop")
Dir.entries(".").select { |file| file.ends_with?('.xlsx') }.each do |file|
  puts "Deleting file #{file}"
  File.delete "#{Dir.pwd}/#{file}"
end
puts "Ended on #{Time.now}"
© www.soinside.com 2019 - 2024. All rights reserved.