DEV Community

Burdette Lamar
Burdette Lamar

Posted on • Edited on

Ruby Method of the Day: #count

Method count returns an integer count of the number of items in a collection that match a given criterion.

The method is available as:

There are three ways to call the method:

  • With no argument and no block, returns the count of items in the collection:
[0, 1, 2].count # => 3
[].count # => 0
Enter fullscreen mode Exit fullscreen mode
  • With argument object, returns the count of items == object in the collection:
[0, 1, 2, 0.0].count(0) # => 2
[0, 1, 2].count(3) # => 0
Enter fullscreen mode Exit fullscreen mode
  • With a block, calls the block with each item in the collection; returns the count of elements for which the block returns a truthy value:
[0, 1, 2, 3].count {|element| element > 1} # => 2
Enter fullscreen mode Exit fullscreen mode

More methods at #rubymethodoftheday.

Top comments (0)