How to get the length of an array using the count method in Ruby
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
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 arraysarr1 = [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 methoda = arr1.countb = arr2.countc = arr3.countd = arr4.count# print the returned valuesputs aputs bputs cputs d