Today I Learned

hashrocket A Hashrocket project

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
See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.