开发者

Testing for membership in a collection

If I know the current_user's answers because the User model has an answers collection:

current_user.answers

How do I test whether that answers collection contains the current answer (ref开发者_运维技巧erenced by the @answer class variable) at each step of a loop?

I was tempted to use the include? method:

current_user.answers.include?(@answer)

but I see it's for mixins :(


You may be best off doing this in the database:

current_user.answers.exists?(@answer.id)

This will execute a select id from answers where id = ? and user_id = ? and return true if it exists.

If you already have answers loaded in memory, include? should work, or any?{|ans| ans.id == @answer.id} or flatten them all out into a set of ids outside the loop:

Set.new(current_user.answers.map(&:id)

and then test for id inclusion inside the loop.


All Enumerable collections (including Arrays, Hashes and Sets) have the include? method to test membership.

[1,2,3].include? 2 # => true
{foo: 'foo', bar: 'bar'}.include? :foo # => true
[1,2,3].include? 5 # => false

(There's also an include? method that modules have, but it's not the same thing.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜