3

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.

1
  • 1
    all methods in String, Array, Hash and Enumerable should be known by heart :-) Commented Nov 1, 2011 at 23:59

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.