How to Use the count Method in Ruby

09/20/2021

Contents

In this article, you will learn how to use the count method in Ruby.

The count Method

In Ruby, the count method is used to count the number of elements in an array or a string that meet a certain condition. Here’s how to use it:

Using count with Arrays

To count the number of elements in an array, you can simply call the count method on the array object:

my_array = [1, 2, 3, 4, 5]
count = my_array.count
puts count # Output: 5

You can also pass a block to count to count the number of elements that meet a certain condition:

my_array = [1, 2, 3, 4, 5]
count = my_array.count { |n| n.even? }
puts count # Output: 2

In this example, the count method counts the number of even numbers in the array.

Using count with Strings

You can also use the count method with strings to count the number of occurrences of a certain character or set of characters:

my_string = "Hello, World!"
count = my_string.count("l")
puts count # Output: 3

In this example, the count method counts the number of occurrences of the letter “l” in the string.

You can also pass multiple characters to count to count the number of occurrences of any of those characters:

my_string = "Hello, World!"
count = my_string.count("l,o")
puts count # Output: 5

In this example, the count method counts the number of occurrences of the letters “l” or “o” in the string.