gpt4 book ai didi

arrays - 如何扫描数组中除一个索引之外的每个元素?

转载 作者:行者123 更新时间:2023-12-04 13:29:04 25 4
gpt4 key购买 nike

我正在使用 Ruby 2.4。如何扫描数组的每个元素以查找数组中一个索引除外的条件?我试过了

arr.except(2).any? {|str| str.eql?("b")}

但是出现如下错误:

NoMethodError: undefined method `except' for ["a", "b", "c"]:Array

但显然我在网上读到的关于“except”的内容被大大夸大了。

最佳答案

arr.reject.with_index { |_el, index| index == 2 }.any? { |str| str.eql?("b") }

解释:

arr = [0, 1, 2, 3, 4, 5]
arr.reject.with_index { |_el, index| index == 2 }
#=> [0, 1, 3, 4, 5]

缩短你正在做的事情:

arr.reject.with_index { |_el, index| index == 2 }.grep(/b/).any?
#=> true

根据@Cary 的评论,另一个选项是:

arr.each_with_index.any? { |str, i| i != 2 && str.eql?("b") }

关于arrays - 如何扫描数组中除一个索引之外的每个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42565261/

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