In Ruby, one of the ways to get the length of an array is by using the size method. It returns an integer value representing the total number of elements in an array.
array.size
The size method takes no parameters.
The value returned is an integer value which is the number of elements an array contains.
In the code below, we will demonstrate the use of the size method. We created several arrays and got their lengths using the size method.
# create several arraysarr1 = [1, 2, 3, 4, 5]arr2 = ["a", "b", "c", "d", "e", "f", "g", "h"]arr3 = ["FireFox", "Chrome", ]arr4 = []arr5 = ["Google", "Meta", "Netflix", "Apple", "Amazon"]arr6 = ["Java", "Ruby"]# find the length of arrays# using the count methoda = arr1.sizeb = arr2.sizec = arr3.sized = arr4.sizee = arr5.sizef = arr6.size# print the returned valuesputs aputs bputs cputs dputs eputs f
In the code above, 0 is returned for the length of arr4 simply because it is an empty array.