How to find the index of an array with objects in Rails?

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

How can i do this?

+6
source share
3 answers

To find the index:

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

To find an item:

 array.find{ |item| item.parent_id == 55 } 
+10
source
  array.collect{|a| a[:parent_id]==55 ? a : nil}.compact! 

must complete the task. First, collect all the elements that match your criteria in a new array, than delete the elements of false positives (nil).

0
source

I would use Enumerable # select Documents

 results = my_array.select do |item| item[:parent_id] == 55 end 
0
source

Source: https://habr.com/ru/post/906433/


All Articles