How to Get the Length of a Ruby Array?

In Ruby, you can get the length of an array using either Array#length or its alias Array#size. These methods return the total count of elements in an array.

For example:

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

Additionally, you can use the Array#count method for the same purpose when it's used without any arguments:

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

However, Array#count has multiple uses beyond just getting the length of an array.

This post was published 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.