gpt4 book ai didi

ruby - 将 `any?` 和 `include?` 的结果插入数组

转载 作者:太空宇宙 更新时间:2023-11-03 17:28:56 28 4
gpt4 key购买 nike

这个:

arry = %w[cat dog fish]
arry.any? {|s| pp s.include?('sh')}

输出:

false
false
true

当我尝试通过这样做将元素插入数组时,

tester = []
arry = %w[cat dog fish]
arry.any? {|s| tester << s.include?('sh')}

pp tester

它输出:

[false]

只有一个元素被压入。不确定为什么我不能将 include? 的结果推送到数组中。

如何将所有结果都放入数组中?

最佳答案

Enumerable#any?一旦 block 返回 truthy 值,立即退出。

我不确定你为什么要为这个用例使用 any?,但实际情况是:在第一次迭代中, block 返回一个真实的数组。

使用 #each_with_object 甚至简单的 #map 代替:

arry.each_with_object([]) { |s, tester| tester << s.include?('sh') }
arry.map { |s| s.include?('sh') }

我的最爱:

arry.map(&/sh/.method(:!~)).map(&:!)

关于ruby - 将 `any?` 和 `include?` 的结果插入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54041569/

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