There are many ways we can use Ruby to get the length of an array. We can use the length method, the size method, or the count method to get the length of an array. Let’s take a look at using each one.

Let’s take a look at the length method first.

arr.length

And here is a simple example.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

puts numbers.length

#Output
9

The length property is straightforward and one of the easiest ways to get the length of an array. We can use another method that will return the same result as the length method, the size method.

arr.size

Let’s see the size method in action below with our same example.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

puts numbers.size

#Output
9

Finally, let’s look at the count method for finding the length of an array. This will work the same way as the length and size methods.

arr.count

Let’s see the count method in action below with our same example.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

puts numbers.count

#Output
9

When working with arrays, it can be useful to be able to easily calculate the array length and size of an array.

To get the length of an array in Ruby, we can use either the length, size, or count methods.

Let’s see these methods used on a bunch of different arrays.

numbersArray = [32,1,0,9,23,430,1000]
stringsArray = ["This","an","array","of","strings"]
mixedArray = ["Hello","",nil,"null",true,234,"23"]
arr1 = []
arr2 = [""]

puts numbersArray.length
puts numbersArray.size
puts numbersArray.count

puts stringsArray.length
puts stringsArray.size
puts stringsArray.count

puts mixedArray.length
puts mixedArray.size
puts mixedArray.count

puts arr1.length
puts arr1.size
puts arr1.count

puts arr2.length
puts arr2.size
puts arr2.count 

#Output
7
7
7
5
5
5
7
7
7
0
0
0
1
1
1

Hopefully this article has been useful for you to learn how to use Ruby to get the length of array.

Categorized in:

Ruby,

Last Update: March 22, 2024