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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With