仅当所有值在 Ruby 中评估为 true 时才返回 true [英] Return true only if all values evaluate to true in Ruby

查看:40
本文介绍了仅当所有值在 Ruby 中评估为 true 时才返回 true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

验证可枚举的所有元素是否满足特定条件的快速方法是什么?我想从逻辑上讲它会像:

What's a fast way to verify whether all elements of an enumerable satisfy a certain condition? I guess logically it would be like:

elements = [e1, e2, e3, ...]
return (condition on e1) && (condition on e2) && (condition on e3) && ...

例如,如果我有一个整数数组,我想回答所有整数都是奇数吗?"这个问题

For example, if I had an array of integers, and I wanted to answer the question "Are all integers odd?"

我总是可以迭代每个值,检查它是否为真,然后当其中一个返回假时返回假,但有没有更好的方法来做到这一点?

I can always iterate over each value, check whether it's true, and then return false when one of them returns false, but is there a better way to do it?

推荐答案

您可以使用 all? 来自 Enumerable 混入的函数.

You can use the all? function from the Enumerable mix-in.

elements = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
return elements.all? { |elem| elem % 2 != 0 }

或者,如评论中所指出的,如果您专门寻找奇数值,您也可以使用 odd?.

Or, as pointed out in the comments, you could also use odd? if you're looking specificially for odd values.

elements = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
return elements.all?(&:odd?)

这篇关于仅当所有值在 Ruby 中评估为 true 时才返回 true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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