可以使用 `any?` 来检查数组是否为空吗? [英] Is it ok to use `any?` to check if an array is not empty?

查看:34
本文介绍了可以使用 `any?` 来检查数组是否为空吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用any?方法检查数组是否为空是不是很糟糕?

Is it bad to check if an array is not empty by using any? method?

a = [1,2,3]

a.any?
=> true

a.clear

a.any?
=> false

还是使用 unless a.empty 更好??

推荐答案

any? 在某些情况下与 not empty? 不一样.

any? isn't the same as not empty? in some cases.

>> [nil, 1].any?
=> true
>> [nil, nil].any?
=> false

来自文档:

如果块没有给出,Ruby 会添加{|obj| 的隐式块对象}(那个有吗?如果至少,将返回 true集合成员之一不是false 或 nil).

If the block is not given, Ruby adds an implicit block of {|obj| obj} (that is any? will return true if at least one of the collection members is not false or nil).

这篇关于可以使用 `any?` 来检查数组是否为空吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆