What is array.length in Ruby?

Arrays in Ruby come with different methods with different purposes. .length is a popular one. It is popular because in most programming languages, you will come across length as a method or as a property.

In Ruby, the array.length is used to return the number of elements present in an array.

Syntax

array.length

Parameter

The .length method of an array requires no parameter. It only needs the array on which it is called.

Return value

The number of elements present in an array is returned.

Example

In the code below, we will create arrays and call the .length method on them. Finally, we print the returned values to the console.

# create arrays
array1 = [1, 2, 3, 4, 5]
array2 = ["Ruby", "Javascript", "Python"]
array3 = ["a", "b", "c", "d", "e", "f", "g"]
array4 = [["dog", "cat", "rat"], "human", "stars", ["fish", "meat"]]
array5 = [nil]
# save returned values from ".length" method
a = array1.length
b = array2.length
c = array3.length
d = array4.length
e = array5.length
# print values to console
puts "#{array1}.length = #{a}"
puts "#{array2}.length = #{b}"
puts "#{array3}.length = #{c}"
puts "#{array4}.length = #{d}"
puts "#{array5}.length = #{e}"

Free Resources