gpt4 book ai didi

ruby-on-rails - 如何为 Ruby 数组中的多个值执行 find_index?

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

给定一个数组[0, 0, 1, 0, 1],是否有内置方法获取所有大于 0 的值的索引?因此,该方法应返回 [2, 4]

find_index 只返回第一个匹配项。

使用 Ruby 1.9.2。

最佳答案

在 Ruby 1.8.7 和 1.9 中,在没有 block 的情况下调用的迭代器方法返回一个 Enumerator 对象。所以你可以这样做:

[0, 0, 1, 0, 1].each_with_index.select { |num, index| num > 0 }.map { |pair| pair[1] }
# => [2, 4]

单步执行:

[0, 0, 1, 0, 1].each_with_index
# => #<Enumerator: [0, 0, 1, 0, 1]:each_with_index>
_.select { |num, index| num > 0 }
# => [[1, 2], [1, 4]]
_.map { |pair| pair[1] }
# => [2, 4]

关于ruby-on-rails - 如何为 Ruby 数组中的多个值执行 find_index?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8484592/

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