From a pry
session attempting to figure out why Array#count
with a block doesn't return the expected value:
[16] pry(#<Article>)> self.contributions
[
[0] #<Contribution:0x007fbfa8801e10> {
:id => 2,
:article_id => 2,
:contributor_id => 1,
:original_content => "Ut enim",
:original_start => 0,
:created_at => Mon, 15 Apr 2013 04:16:08 UTC +00:00,
:updated_at => Mon, 15 Apr 2013 04:16:08 UTC +00:00,
:contrib_type => "lock",
:original_length => 7,
:submit_comment => nil,
:related_text => nil
}
]
[17] pry(#<Article>)> self.contributions.count
1
[18] pry(#<Article>)> self.contributions.count {|item| item[:contrib_type] == 'lock'}
1
[19] pry(#<Article>)> self.contributions.count {|item| item[:contrib_type] != 'lock'}
1
Note that self.contributions
contains a single record, with an id
value of 2
and a contrib_type
value of lock
. Fine. The call to self.contributions.count
at [17]
gives the expected (and correct) 1
.
But then we go into the weeds, and stay there. The Ruby documentation for Array#count
states that if a block is given, the method "counts the number of elements yielding a true value." If that's true, then why does the call at [19]
give a value of 1
? Even if that were correct, why would the call at [18]
, testing the exact opposite condition, also return 1
?
If someone can point out the error of my ways, I'd greatly appreciate it...
Assuming this is Rails, it's probably not an
Array
but anActiveRecord
association instance.In this case, the
count
method just calls an SQL query to perform the account and ignores the block. It's not the same asArray#count
.