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.
array.length
The .length method of an array requires no parameter. It only needs the array on which it is called.
The number of elements present in an array is returned.
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 arraysarray1 = [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" methoda = array1.lengthb = array2.lengthc = array3.lengthd = array4.lengthe = array5.length# print values to consoleputs "#{array1}.length = #{a}"puts "#{array2}.length = #{b}"puts "#{array3}.length = #{c}"puts "#{array4}.length = #{d}"puts "#{array5}.length = #{e}"