How to find the length of an array using the size method

Overview

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.

Syntax

array.size

Parameters

The size method takes no parameters.

Return value

The value returned is an integer value which is the number of elements an array contains.

Code example

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 arrays
arr1 = [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 method
a = arr1.size
b = arr2.size
c = arr3.size
d = arr4.size
e = arr5.size
f = arr6.size
# print the returned values
puts a
puts b
puts c
puts d
puts e
puts f

In the code above, 0 is returned for the length of arr4 simply because it is an empty array.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources