How to Count the Number of Elements in an Array in Ruby?

You can get the total count of the number of elements in a Ruby array by using the Array#length, Array#count or Array#size method. Using either of the three will give you the length of an array.

For example:

puts [1, 2, 3].length #=> 3
puts [1, 2, 3].count #=> 3
puts [1, 2, 3].size #=> 3
puts [].length #=> 0
puts [].count #=> 0
puts [].size #=> 0

For the purpose of getting the count of elements in an array, all three methods will produce the same result.

While Array#size is merely an alias for Array#length, the Array#count method can be used in two other ways besides counting the total number of items in an array:

  1. To count the number of times a value occurs in an array;
  2. To count the total number of items in an array that satisfy a condition.

This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.