gpt4 book ai didi

ruby-on-rails - ruby 的 "any?"和 "all?"方法在空数组和哈希上的行为

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

首先,我在有关这些方法的文档中找到了两篇有用的文章:

all?: Passes each element of the collection to the given block. The method returns true if the block never returns false or nil.

any?: Passes each element of the collection to the given block. The method returns true if the block ever returns a value other than false or nil.

但是如果数组和散列为空,我会得到:

irb(main):004:0> [nil, "car", "bus"].all?
=> false
irb(main):005:0> ["nil", "car", "bus"].all?
=> true
irb(main):006:0> [].all?
=> true
irb(main):007:0> ["nil", "car", "bus"].any?
=> true
irb(main):008:0> [nil, "car", "bus"].any?
=> true
irb(main):009:0> [nil].any?
=> false
irb(main):010:0> [].any?
=> false

有人可以向我解释为什么空数组在 any? 方法的情况下给我 false 而在 的情况下给我 true全部?

最佳答案

The method returns true if the block never returns false or nil.

既然 block 永远不会被调用,当然它永远不会返回 false 或 nil,因此 all 返回 true。

同样适用于any:

The method returns true if the block ever returns a value other than false or nil.

由于 block 永远不会被调用,它永远不会返回 false 或 nil 以外的值,因此 any 返回 false。

关于ruby-on-rails - ruby 的 "any?"和 "all?"方法在空数组和哈希上的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13249872/

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