Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.count with block does not return correct answer

I have an array of Assignment objects that I create from a database call:

@assignments = @player.assignments 

I want to count them with this:

@assignments.count {|x| x.sets == 0.0}

This should count the number of assignments with 0.0 sets. However, this always returns the total number of objects in @assignments. I have checked that

@assignments.each {|x| puts x.sets == 0.0}

does not return true in all the cases. Any clues?

Edit>

@assignments.map(&:sets)
=> [35.0, 120.0, 0.0, 0.0, 0.0, 0.0, 0.0, 12.0, 75.0, 0.0, 0.0, 0.0, 0.0] 
like image 596
user1742188 Avatar asked Aug 19 '13 08:08

user1742188


Video Answer


2 Answers

Most likely, @assignments is not an Array instance, but ActiveRecord::Relation, try @assignments.class. If so, count method does not work as you expected, it returns numbers of records.

Try

@assignments.where(sets: 0).count

Or even (convert to array first)

@assignments.to_a.count {|x| x.sets == 0.0}
like image 174
dimuch Avatar answered Oct 22 '22 09:10

dimuch


Try with this:

    @assignments.select {|x| x if x.sets == 0.0}.count

Thanks

like image 23
Rails Guy Avatar answered Oct 22 '22 10:10

Rails Guy