Ruby根据属性在数组中查找并返回对象 [英] Ruby find and return objects in an array based on an attribute

查看:213
本文介绍了Ruby根据属性在数组中查找并返回对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果某个属性正确,如何遍历对象数组并返回整个对象?

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

我的Rails应用程序中有以下内容

I have the following in my rails app

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

array_of_objects.each { |favor| favor.completed }

但是由于某种原因,这两个返回相同的结果!我试图用collectmapkeep_if以及!favor.completed而不是favor.completed == false替换each,但它们都不起作用!

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!

推荐答案

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

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

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

您也可以使用find_all代替select.

这篇关于Ruby根据属性在数组中查找并返回对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆