DEV Community

Burdette Lamar
Burdette Lamar

Posted on • Edited on

1

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.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs