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
This is already available with Enumerable#find_all:
a = (1âŠ10).to_a
puts a.find_all {|v| v < 5 }.size
4
Ian
···
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 }
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
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.
Once you assimilate the idiom they arenât too bad. Readability only
âhappensâ when a reader looks at something, I donât think itâs an
inherent property of the material being read.