4

i am trying to count an # of objects in an array using a block, like this:

cc = u.cookies.count {|n| n.opened}

This return 3, which is wrong. I went a step further, and did this:

cc = u.cookies.count {|n| false}

which should always return 0, but it returns 3!!!.

This return 0, just like it should:

[1,2,3,4].count {|n| false}

Here's my user model:

class User < ActiveRecord::Base
    has_many :cookies
end

What's going on? Thanks

0

1 Answer 1

3

u.cookies is ActiveRecord::Relation, not an array.

So what ever the block is, the result won't change, you need to do:

cc = u.cookies.where(:opened => true).count
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.