Ruby文件是否存在

在 Ruby 中,我们要判断一个文件是否存在可以使用 exists 方法。

exists方法

语法

File::exists?(filename)

参数

模式 描述
filename 文件名。

说明

判断文件是否存在。

案例

判断文件是否存在

使用 exists 方法判断文件是否存在

#!/usr/bin/ruby -w # -*- coding : utf-8 -*- puts "HaiCoder(www.haicoder.net)" exists1 = File::exists?("text.txt") exists2 = File::exists?("input.txt") print("exist1 = ", exists1, " exist2 = ", exists2, "\n")

程序运行后,控制台输出如下:

12_Ruby文件是否存在.png

我们使用了 exist 方法判断了文件是否存在。

Ruby exists方法总结

在 Ruby 中,我们要判断一个文件是否存在可以使用 exists 方法。