为什么.all?在空数组上返回真? [英] Why does .all? return true on an empty array?

查看:57
本文介绍了为什么.all?在空数组上返回真?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Ruby 评估数组中的所有项,如果它们都通过条件测试,则返回 true.

Using Ruby I want to evaluate all items in an array, and return true if they all pass a conditional test.

我可以使用例如array.all?{ |值|值 == 2 }

所以:

> array=[2,2]
> array.all? { |value| value == 2 }
=> true
> array=[2,3]
> array.all? { |value| value == 2 }
=> false

太好了!

但是,为什么一个空数组可以通过这个测试?

But, why does an empty array pass this test?

> array=[]
> array.all? { |value| value == 2 }
=> true

这不应该返回false吗?

Shouldn't this return false?

如果我需要它返回false,我应该如何修改方法?

And if I need it to return false, how should I modify the method?

推荐答案

在 Ruby 中,您永远无法循环遍历空集合(数组、散列等),因此在您的情况下,您的块永远不会被执行.如果块永远不会被执行,all? 返回真(没有条件使结果为假).

In Ruby you can never loop over an empty collection (array, hashes, etc.), so in your case your block never gets executed. And if the block never gets executed, all? returns true (there is no condition to make the result false).

阅读Ruby 文档all?/a>.

您可以通过以下方式轻松实现目标

You can simply achieve your goal by

  !array.empty? && array.all? { |value| value == 2 }

这篇关于为什么.all?在空数组上返回真?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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