Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

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!

question from:https://stackoverflow.com/questions/35105228/ruby-find-and-return-objects-in-an-array-based-on-an-attribute

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...