3

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

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

但出现以下错误:

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

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

4

1 回答 1

4
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") }
于 2017-03-02T20:27:04.657 回答