Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

array
ruby
communitycreator

How to get the length of an array using the count method in Ruby

okwudili onyejiaku

Overview

The count method in Ruby is used to check the length of an array. The length of an array is the number of elements the array contains.

Syntax

Let’s view the syntax of count in Ruby.

array.count
count syntax in ruby

Parameters

This method takes no parameters.

Return Value

This method returns an integer that represents the length of the array.

Code

In the code below, we shall demonstrate the use of the count method by creating several arrays and finding their lengths.

# create several arrays
arr1 = [1, 2, 3, 4, 5]
arr2 = ["a", "b", "c", "d", "e", "f", "g", "h"]
arr3 = ["FireFox", "Chrome", ]
arr4 = ["Google", "Meta", "Netflix", "Apple", "Amazon"]

# find the length of arrays
# using the count method
a = arr1.count
b = arr2.count
c = arr3.count
d = arr4.count

# print the returned values
puts a
puts b
puts c
puts d
Try it out yourself!

RELATED TAGS

array
ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring