1

I'm trying to write one line of code to tell me if there is an element in an array that meets a set of criteria and then breaks on true.

For example

I have [1,2,3,4,5,6,7,8,9,10,11,12] and I want to find the first element that is divisible by 2 and 3. I want to write a one liner that will return true as soon as it hits 6 and not process the remaining elements in the array.

I can write a for each loop and break, but I feel like there should be a way to do that in one line of code.

1
  • If it is divisible by both 3 and 2, then it is divisible by 6. Use #find or #any depending on what you want to know (the same block will work) [...].find { |n| n % 6 == 0 } Commented Feb 12, 2012 at 8:40

2 Answers 2

5

any?:

[1,2,3,4,5,6,7,8,9,10,11,12].any?{|e| e % 2 == 0 && e % 3 == 0}

or you can combine it with all? and have a great tutorial example:

[1,2,3,4,5,6,7,8,9,10,11,12].any?{|e| [2, 3].all?{|d| e % d == 0}}

And if you actually need the first matching element returned, use find:

[1,2,3,4,5,6,7,8,9,10,11,12].find{|e| [2,3].all?{|d| e % d == 0}}
# => 6 
Sign up to request clarification or add additional context in comments.

2 Comments

any? doesn't return the value, it only checks if there is such a value
any? returns a boolean value, which actually answers OP's question: if there is an element in an array that meets a set of criteria.
4

You should use: find

[1,2,3,4,5,6,7,8,9,10,11,12].find{|e| e % 2 == 0 && e % 3 == 0}

It will return 6, and it won't process the values after 6.

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.