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 AssemblyAI

Automatic Speech Recognition with AssemblyAI

Experience near-human accuracy, low-latency performance, and advanced Speech AI capabilities with AssemblyAI's Speech-to-Text API. Sign up today and get $50 in API credit. No credit card required.

Try the API

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

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay