From: Stefan Arentz Date: 2003-07-05T09:01:49+09:00 Subject: Re: Ruby Code Snippet: Array.count Ian Macdonald writes: > On Sat 05 Jul 2003 at 08:01:38 +0900, Stefan Arentz wrote: > > > > > Maybe this functionality is already somewhere in Ruby, but I could not > > find it. This little snippet extends Array with a count method. It takes > > a code block that can be used to count elements that match a specific > > condition: > > > > a = Array[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] > > puts a.count { |v| v < 5 } > > This is already available with Enumerable#find_all: > > a = (1..10).to_a > puts a.find_all {|v| v < 5 }.size > > 4 Yes but this is very inefficient if you have large collections. My version does not need to create a new temporary collection just to count it. S.