Ruby基于属性查找并返回数组中的对象

时间:2021-11-23 22:31:28

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

我在rails应用程序中有如下内容

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!

但是出于某种原因,这两个函数会返回相同的结果!我试着用collect、map、keep_if以及!favor.complete来替换它们,而不是帮助。完成== false,没有一个工作!

Any help is highly appreciated!

非常感谢您的帮助!

3 个解决方案

#1


14  

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

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

将返回已完成的所有对象为false。

You can also use find_all instead of select.

您还可以使用find_all而不是select。

#2


10  

For first case,

对于第一种情况,

array_of_objects.reject(&:completed)

For second case,

第二个案例,

array_of_objects.select(&:completed)

#3


1  

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

您需要使用Enumerable#find_all来获取所有匹配的对象。

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

#1


14  

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

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

将返回已完成的所有对象为false。

You can also use find_all instead of select.

您还可以使用find_all而不是select。

#2


10  

For first case,

对于第一种情况,

array_of_objects.reject(&:completed)

For second case,

第二个案例,

array_of_objects.select(&:completed)

#3


1  

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

您需要使用Enumerable#find_all来获取所有匹配的对象。

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