gpt4 book ai didi

ruby - 检查 Ruby 中的目录是否为空

转载 作者:数据小太阳 更新时间:2023-10-29 06:26:46 24 4
gpt4 key购买 nike

在 Ruby 中如何检查目录是否为空?有没有类似的东西:

Dir.exists?("directory")

(我知道那个函数不存在。)

最佳答案

Ruby 现在有 Dir.empty? ,使这变得非常简单:

Dir.empty?('your_directory') # => (true|false)

在 2.4.0 之前的 Rubies 中,您可以只获取条目列表并自行查看它是否为空(考虑“.”和“..”)。参见 the docs .

(Dir.entries('your_directory') - %w{ . .. }).empty?

# or using glob, which doesn't match hidden files (like . and ..)
Dir['your_directory/*'].empty?

更新:上面的第一个方法使用了正则表达式;现在它没有(显然)。下面的评论主要适用于以前的(正则表达式)版本。

关于ruby - 检查 Ruby 中的目录是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5059156/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com