Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First element of an array with condition

Tags:

arrays

ruby

Is there a shorter way to find the first element in an array meeting some conditions than this:

my_array[ my_array.index {|x| x.some_test} ] 
like image 375
Balzard Avatar asked Nov 12 '12 07:11

Balzard


People also ask

How do I find the first element of an array?

There are several methods to get the first element of an array in PHP. Some of the methods are using foreach loop, reset function, array_slice function, array_values, array_reverse, and many more. We will discuss the different ways to access the first element of an array sequentially.

How do you check the condition of an array?

To check if any value in JavaScript array satisfies the condition you can use Array. prototype. some() method. It returns true if any item in array satisfies the condition else returns false .

How do you define an array with conditional elements?

Call Array. Another way to conditionally add items conditionally to a JavaScript array is to use the push method. Then 'bar' is appended to items but 'false' isn't . This is because the first conditionally has true as the conditional and the 2nd one has false as the condition. Therefore items is [“foo”, “bar”] again.

What is the first element in an array called?

The memory address of the first element of an array is called first address, foundation address, or base address. Because the mathematical concept of a matrix can be represented as a two-dimensional grid, two-dimensional arrays are also sometimes called matrices.


2 Answers

Try this:

my_array.find{|x| x.some_test } 

Or here's a shortcut (thanks @LarsHaugseth for reminding about it)

my_array.find(&:some_test) 
like image 76
Sergio Tulentsev Avatar answered Oct 05 '22 06:10

Sergio Tulentsev


As for me find sounds confusing. As i am expecting receive more than one object for such a request.

I prefer to use detect for getting distinct one.

And select for finding all of them.

Here what ruby docs tells about them:

detect(ifnone = nil) {| obj | block } → obj or nil click to toggle source  find(ifnone = nil) {| obj | block } → obj or nil  detect(ifnone = nil) → an_enumerator  find(ifnone = nil) → an_enumerator 

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.

find_all {| obj | block } → array click to toggle source select {| obj | block } → array find_all → an_enumerator select → an_enumerator 

Returns an array containing all elements of enum for which block is not false

like image 26
sarvavijJana Avatar answered Oct 05 '22 06:10

sarvavijJana