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

Find out how to get the length of 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.

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.

Hope you found this post useful. It was published . Please show your love and support by sharing this post.