1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 15:18:01 +00:00
Files
til/ruby/pass-a-block-to-count.md
2015-12-31 10:50:32 -06:00

558 B

Pass A Block To Count

Ruby's Enumerable module comes with the method #count for determining how many items are in an array or hash.

> [1,2,3].count
=> 3
> {a: 1, b: 2}.count
=> 2

The #count method has a trick up its sleeve though. It can take a block with a predicate that returns true or false. It essentially acts like #select returning the count rather than the array subset itself.

> [1,2,3].count { |x| x.odd? }
=> 2
> {a: 1, b: 2}.count { |(x,y)| y < 0 }
=> 0