Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

array
length
ruby
communitycreator

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

okwudili onyejiaku

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.

RELATED TAGS

array
length
ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring