Ruby find and return objects in an array based on an attribute

后端 未结 3 594
后悔当初
后悔当初 2021-02-05 01:20

How can you iterate through an array of objects and return the entire object if a certain attribute is correct?

I have the following in my rails app

arr         


        
相关标签:
3条回答
  • 2021-02-05 01:31
    array_of_objects.select { |favor| favor.completed == false }
    

    Will return all the objects that's completed is false.

    You can also use find_all instead of select.

    0 讨论(0)
  • 2021-02-05 01:51

    You need to use Enumerable#find_all to get the all matched objects.

    array_of_objects.find_all { |favor| favor.completed == false }
    
    0 讨论(0)
  • 2021-02-05 01:53

    For first case,

    array_of_objects.reject(&:completed)
    

    For second case,

    array_of_objects.select(&:completed)
    
    0 讨论(0)
提交回复
热议问题