Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find the index of an array that has objects in Rails?

I have an array of objects and I want to find which element in the array has a particular attribute equal to a value, specifically which element in this array has an object that has :parent_id equal to 55.

How can I do this?

like image 256
Shamoon Avatar asked Jan 19 '12 22:01

Shamoon


People also ask

How do you find the index of an object in an array of objects?

To find the index of an object in an array, by a specific property: Use the map() method to iterate over the array, returning only the value of the relevant property. Call the indexOf() method on the returned from map array. The indexOf method returns the index of the first occurrence of a value in an array.

How do you find the index of an array array?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found. The following illustrates the syntax of the indexOf() method.

How do you find the index of an array element in Ruby?

Ruby | Array class find_index() operation Array#find_index() : find_index() is a Array class method which returns the index of the first array. If a block is given instead of an argument, returns the index of the first object for which the block returns true.

How do you find the index of an element?

indexOf() The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.


1 Answers

To find the index:

 array.index{ |item| item.parent_id == 55 }

To find the item:

array.find{ |item| item.parent_id == 55 }
like image 139
dantswain Avatar answered Oct 20 '22 17:10

dantswain