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!
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.
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.
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 .
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.
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
.
For first case,
array_of_objects.reject(&:completed)
For second case,
array_of_objects.select(&:completed)
You need to use Enumerable#find_all
to get the all matched objects.
array_of_objects.find_all { |favor| favor.completed == false }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With