Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...