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

时间:2017-03-02 20:24:48

标签: arrays ruby any ruby-2.4

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

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

但是出现了以下错误:

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

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

1 个答案:

答案 0 :(得分:2)

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") }
相关问题