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.
Let’s view the syntax of count
in Ruby.
array.count
This method takes no parameters.
This method returns an integer that represents the length of the array.
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