Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding first value in an array which does not have a specific value

Tags:

ruby

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.

like image 363
PlankTon Avatar asked Dec 06 '25 10:12

PlankTon


1 Answers

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.

like image 62
Anurag Avatar answered Dec 10 '25 22:12

Anurag