fardin
fardin

Reputation: 1477

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

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

array_of_objects.each { |favor| favor.completed == false }

array_of_objects.each { |favor| favor.completed }

but for some reason these two return the same result! I have tried to replace each with collect, map, keep_if as well as !favor.completed instead of favor.completed == false and none of them worked!

Any help is highly appreciated!

Upvotes: 60

Views: 78058

Answers (4)

prajeesh
prajeesh

Reputation: 2382

For newer versions of ruby, you can use filter method

array_of_objects.filter { |favor| favor.completed == false }

Reference: https://apidock.com/ruby/Array/filter

Upvotes: 0

Wand Maker
Wand Maker

Reputation: 18762

For first case,

array_of_objects.reject(&:completed)

For second case,

array_of_objects.select(&:completed)

Upvotes: 15

Babar Al-Amin
Babar Al-Amin

Reputation: 3984

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.

Upvotes: 77

Arup Rakshit
Arup Rakshit

Reputation: 118271

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

array_of_objects.find_all { |favor| favor.completed == false }

Upvotes: 3

Related Questions