3

I'm using Ruby 2.4. How do I scan every element of an array for a condition except one index in the array? I tried this

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

But got the following error:

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

but evidently what I read online about "except" is greatly exaggerated.

Andrey Deineko
  • 51,333
  • 10
  • 112
  • 145
Dave
  • 15,639
  • 133
  • 442
  • 830
  • 1
    What exactly did you read about `except`, and where? Ruby arrays have no such method. Also, calling `.eql?` on strings is not terribly idiomatic; you can just do `str == "b"`. – Mark Reed Mar 02 '17 at 20:28
  • I found a post where someone defines such a method themselves, but even there it is based on the value of the element, not its index. – Mark Reed Mar 02 '17 at 20:33
  • 1
    [is this the one? :)](https://coderwall.com/p/skzsoa/ruby-array-except) – Andrey Deineko Mar 02 '17 at 20:34
  • @MarkReed wouldn't `eql` be idiomatic to ruby considering most languages use some form of `==`? It also reads more like natural language. – max pleaner Mar 02 '17 at 20:48
  • 1
    `.eql?` is certainly Ruby, but using it to compare Strings is not typical in Ruby code - which is what I meant by "idiomatic Ruby". *As long as both objects being compared are Strings*, `eql?` and `==` and `===` all perform the same comparison. And since far more languages use `==` for comparison than any of the others, it's usually considered the most natural choice. – Mark Reed Mar 02 '17 at 21:05

1 Answers1

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

Explanation:

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

Shortening what you are doing:

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

Following the @Cary's comment, another option would be:

arr.each_with_index.any? { |str, i| i != 2 && str.eql?("b") }
Andrey Deineko
  • 51,333
  • 10
  • 112
  • 145