diff --git a/README.md b/README.md index b568eb1..462523d 100644 --- a/README.md +++ b/README.md @@ -205,6 +205,7 @@ smart people at [Hashrocket](http://hashrocket.com/). - [Next And Previous Floats](ruby/next-and-previous-floats.md) - [Override The Initial Sequence Value](ruby/override-the-initial-sequence-value.md) - [Parallel Bundle Install](ruby/parallel-bundle-install.md) +- [Pass A Block To Count](ruby/pass-a-block-to-count.md) - [Passing Arbitrary Methods As Blocks](ruby/passing-arbitrary-methods-as-blocks.md) - [Passing Arguments To A Rake Task](ruby/passing-arguments-to-a-rake-task.md) - [Percent Notation](ruby/percent-notation.md) diff --git a/ruby/pass-a-block-to-count.md b/ruby/pass-a-block-to-count.md new file mode 100644 index 0000000..f305ff2 --- /dev/null +++ b/ruby/pass-a-block-to-count.md @@ -0,0 +1,23 @@ +# Pass A Block To Count + +Ruby's [`Enumerable`](http://ruby-doc.org/core-2.2.3/Enumerable.html) module +comes with the method `#count` for determining how many items are in an +array or hash. + +```ruby +> [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. + +```ruby +> [1,2,3].count { |x| x.odd? } +=> 2 +> {a: 1, b: 2}.count { |(x,y)| y < 0 } +=> 0 +```