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.

Image of Stellar post

Check out Episode 1: How a Hackathon Project Became a Web3 Startup 🚀

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

Top comments (0)

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

👋 Kindness is contagious

If you found this post useful, please drop a ❤️ or a friendly comment!

Okay.