Step 16: Length


Arrays have a method, aptly named .length, that allows us to get the length of the array. Try not to get confused by zero-indexing and length. If an array has 6 items, its length will be 6 but the last item will be at index 5.

puts([1, 2, 3, 4, 5].length)

It can be useful to use the length method to help us get the last item in an array.

my_array = [1, 2, 3, 4, 5]
puts(my_array[my_array.length - 1])

Notice how we subtracted one from the length of my_array to get the index of the last item in the array. Array length is also important and useful when we want to loop through each item in an array and stop when we get to the end.

ciudades_colombianos = ["Medellín", "Bogotá", "Cartagena", "Barranquilla", "Cali"]


ind = 0


while ind < ciudades_colombianos.length
    puts(ciudades_colombianos[ind])
    ind = ind + 1
end