都做吗?有吗?保证短路评估? [英] Do all? and any? guarantee short-circuit evaluation?

查看:42
本文介绍了都做吗?有吗?保证短路评估?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

pryirb 中测试一些代码,我得到以下结果:

Testing out some code in both pry and irb, I get the following results:

[1] pry(main)> a = [1, 3, 5, 7, 0]
=> [1, 3, 5, 7, 0]
[2] pry(main)> a.any? {|obj| p obj; 3 / obj > 1}
1
=> true
[3] pry(main)> a.all? {|obj| p obj; 3 / obj > 1}
1
3
=> false

[2][3] 我看到似乎有短路评估会尽快中止迭代,但这是有保证的行为吗?阅读文档没有提到这种行为.我意识到我可以使用 inject 代替,因为它会遍历所有内容,但我很想知道官方的 Ruby 视图是什么.

In [2] and [3] I see that there appears to be short-circuit evaluation that aborts the iteration as soon as possible, but is this guaranteed behaviour? Reading the documentation there is no mention of this behaviour. I realise that I can use inject instead as that will iterate over everything, but I'm interested in finding out what the official Ruby view is.

推荐答案

是.

在 Ruby 标准的最终草案中,all? 定义如下:

In the final draft of the Ruby standard, all? is defined as such:

  1. 在接收器上调用each方法
  2. 对于方法 each 产生的每个元素 X:
  1. Invoke the method each on the receiver
  2. For each element X which the method each yeilds:
  1. 如果给出了块,则以 X 作为参数调用块.如果这个调用返回一个虚假的对象,return false.
  2. 如果块没有给出,并且 X 是一个虚假的对象,返回 false.

  • 返回true.
  • 注意步骤 2 中的 return 这个词.这保证了短路评估.any? 的定义类似.然而,该标准仍然是一个草案,我不知道哪些 Ruby 实现(如果有)旨在符合标准.

    Note the word return in step 2. This guarantees short circuit evaluation. any? is defined similarly. However the standard is still a draft and I don't know which Ruby implementations (if any) aim to be standards-compliant.

    这篇关于都做吗?有吗?保证短路评估?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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