From: Intransition Date: 2009-11-05T23:34:42+09:00 Subject: Re: Hash#count On Nov 4, 11:32 am, Paul Smith wrote: > On Wed, Nov 4, 2009 at 4:19 PM, Intransition wrote: > > I want to suggest Hash#count be defined such that it counts hash > > values. A it stands (using Enumerable#count) it only can ever return 0 > > or 1. > > > Current: > > >  {:a=>1,:b=2,:c=>1}.count([:a,1]) #=> 1 > >  {:x=>1,:b=2,:c=>1}.count([:a,1]) #=> 0 > >  {:a=>1,:b=2,:c=>1}.count(1)      #=> 0 > > {:a=>1,:b=2,:c=>1}.count{|x| x[1]==1}      #=> 2 Sure. And there other ways to do it too. My point is not that there is a difficulty in achieving this behavior that must be addressed, but that Hash#count (without using a block) is much less useful as currently defined. My suggestion is simply to maximize it's utility for the majority of usecases. This is not unlike what other Enumerable Hash methods do. Consider Hash#include?. It has a Hash specific definition whereby it checks only keys. Let me put it another way. There is no point in counting Hash keys. There is only ever one or none. So Hash#count should only count values. Now one might ask about counting all pairs with keys matching a pattern, but such cases are going to be the exception rather then the rule, and can be achieved almost as simply using other means, for instance: hash.to_a.count{ |(k,v)| ... } or hash.keys.count{ |k| hash[k] =~ /.../ } Oh, and b/c of enumerators, I think we can even do: hash.each.count{ |k,v| ... } T.