Reputation: 12605
Simple question I suspect, but nonetheless:
I'm looking for an efficient way to grab the first element from an array that does not have a particular value. So for example, given
["Fred", "Fred", "Fred", "James", "Alex", "Fred"]
I'd like to return "James"
I can do this via something like
thearray.select { |i| i != "Fred" }.first
but that's going to iterate over every element (including alex and the last fred) before returning the value.
So - I'm hoping for a simple way to do this that won't iterate through the entire array - just until it finds a value. Any ideas apprecated.
Upvotes: 3
Views: 1122
Reputation: 141879
Use detect
or find
.
array.detect { |value| value != "Fred" }
According to the documentation, it returns the first matching value.
Passes each entry in enum to block. Returns the first for which block is not false. If no object matches, calls ifnone and returns its result when it is specified, or returns nil otherwise. If no block is given, an enumerator is returned instead.
Upvotes: 10