如何检查文件是否存在

M. *_*dam 2 ruby

所以我的问题基本上是如果找不到作为参数给出的文件,我无法找出给出错误消息的条件。

if ARGV.empty?
    puts "Give me a file!"
elseif [condition]
    puts "Can't find the file"
else
    file = File.open(ARGV[0])
Run Code Online (Sandbox Code Playgroud)

我真正需要的是 elseif 的条件。

And*_*ell 8

尝试File.exist?,例如

2.3.0 :003 > File.exist? 'foo'
 => false 
Run Code Online (Sandbox Code Playgroud)