Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 924
fardin Avatar asked Jan 30 '16 18:01

fardin


People also ask

How do you access an array of objects in Ruby?

The at() method of an array in Ruby is used to access elements of an array. It accepts an integer value and returns the element. This element is the one in which the index position is the value passed in.

What does .select do in Ruby?

Array#select() : select() is a Array class method which returns a new array containing all elements of array for which the given block returns a true value. Return: A new array containing all elements of array for which the given block returns a true value.

What is .last in Ruby?

last() is a Array class method which returns the last element of the array or the last 'n' elements from the array. The first form returns nil, If the array is empty .

What is .first in Ruby?

Ruby | Array class first() function first() is a Array class method which returns the first element of the array or the first 'n' elements from the array.


3 Answers

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.

like image 132
Babar Al-Amin Avatar answered Oct 15 '22 05:10

Babar Al-Amin


For first case,

array_of_objects.reject(&:completed)

For second case,

array_of_objects.select(&:completed)
like image 36
Wand Maker Avatar answered Oct 15 '22 05:10

Wand Maker


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

array_of_objects.find_all { |favor| favor.completed == false }
like image 2
Arup Rakshit Avatar answered Oct 15 '22 05:10

Arup Rakshit