使用FileUtils方法失败会发生什么?

时间:2016-06-17 00:38:55

标签: ruby fileutils

如果我没有传递options哈希中的任何选项,那么FileUtils在失败时会如何表现?

我尝试在ruby-doc.orgAPIdock上查看FileUtils但找不到任何内容。

1 个答案:

答案 0 :(得分:0)

  

FileUtils失败时的行为如何?

好吧,让我们看看:

require 'FileUtils'

puts Dir.pwd
#Existing dir:
FileUtils.cd("../python_programs")
puts Dir.pwd
FileUtils.cd("/does/not/exist")

--output:--
/Users/7stud/ruby_programs
/Users/7stud/python_programs
....`chdir': No such file or directory @ dir_chdir - /does/not/exist (Errno::ENOENT)

所以......你可以这样做:

require 'FileUtils'

begin
  FileUtils.cd("/does/not/exist")
rescue Errno::ENOENT
  puts "Couldn't switch directories"
end

--output:--
Couldn't switch directories

或者,即便如此:

require 'FileUtils'

paths = %w[
  ../python_programs
  /does/not/exist
  ../rails_projects
]

paths.each do |path|
  begin
    FileUtils.cd(path)
    puts "Just switched directories to: #{Dir.pwd}"
  rescue Errno::ENOENT
    puts "Couldn't switch to directory: #{path}"
  end
end

--output:--
Just switched directories to: /Users/7stud/python_programs
Couldn't switch to directory: /does/not/exist
Just switched directories to: /Users/7stud/rails_projects