Ruby - Find the Length of an Array

1. Introduction

Arrays are one of the fundamental data structures in programming. They can hold multiple items, and often, one of the basic operations you might need to perform is finding out how many items (or elements) are inside an array. In Ruby, this task is straightforward thanks to its built-in methods. In this post, we'll demonstrate how to determine the length (or size) of an array in Ruby.

2. Program Steps

1. Define or initialize an array.

2. Use the length or size method of the array to get its length.

3. Print the length to the console.

3. Code Program

# Define an array
sample_array = [10, 20, 30, 40, 50]
# Find the length of the array
array_length = sample_array.length
# Output the length
puts "The length of the array is: #{array_length}"


The length of the array is: 5


1. sample_array = [10, 20, 30, 40, 50]: Here, we define an array named sample_array containing five integers.

2. sample_array.length: The length method returns the number of elements in the array. In Ruby, you can also use the size method as an alias for length.

3. puts: This is used to print the result to the console.

Thus, with just a few lines of code, Ruby allows you to efficiently determine the number of elements in an array.