From: Dave Thomas Date: 2003-07-05T13:20:35+09:00 Subject: Re: Ruby Code Snippet: Array.count 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 } > > ==> 4 > > The code: > > class Array > def count(&action) > count = 0 > self.each { |v| count = count + 1 if action.call(v) } > return count > end > end I'm starting to like using 'inject' for this kind of thing, but it isn't as clear to read: class Array def count inject(0) {|sum, e| yield(e) ? sum + 1 : sum } end end > Ruby is sweet :-) Agreed :) Cheers Dave