How to get length of an array in Ruby
In this tutorial, we will learn how to get the length of an array in Ruby.
The length of an array means the total number of elements present in a given array.
Using length method
To get the length of an array, we can use the built-in length
method in Ruby.
The
length
method returns the number of elements in an array in integer format.
Here is an example, that gets the length of a prices
array:
prices = [10, 40, 80]
length = prices.length
puts length
Output:
3
Alternatively, we can also use the size
method in ruby to get the length of an given array.
prices = [10, 40, 80]
length = prices.size
puts length