Ruby 根据属性查找并返回数组中的对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35105228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby find and return objects in an array based on an attribute
提问by fardin
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 eachwith collect, map, keep_ifas well as !favor.completedinstead of favor.completed == falseand none of them worked!
但出于某种原因,这两个返回相同的结果!我试图取代each有collect,map,keep_if以及!favor.completed,而不是favor.completed == false和他们没有工作!
Any help is highly appreciated!
任何帮助都非常感谢!
回答by Babar
array_of_objects.select { |favor| favor.completed == false }
Will return all the objects that's completed is false.
将返回所有完成的对象是假的。
You can also use find_allinstead of select.
您也可以使用find_all代替select。
回答by Wand Maker
For first case,
对于第一种情况,
array_of_objects.reject(&:completed)
For second case,
对于第二种情况,
array_of_objects.select(&:completed)
回答by Arup Rakshit
You need to use Enumerable#find_allto get the all matched objects.
您需要使用Enumerable#find_all来获取所有匹配的对象。
array_of_objects.find_all { |favor| favor.completed == false }

