What's the Difference Between Array #count(), #size() and #length() in Ruby?

The Ruby Array#size method is an alias for Array#length; they can be used interchangeably. They both return the number of elements in an array. For the purpose of getting the count of elements in an array, all three methods (Array#size, Array#length and Array#count) produce the same result:

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

However, 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; for example:
    puts [3, 3, 4, 3, 3, 5, 5].count(3) #=> 4
    
  2. To count the total number of items in an array that satisfy a condition; for example:
    numbers = [3, 2, 5, 6, 1, 7, 8]
    
    puts numbers.count { | item | item < 4 } #=> 3
    

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.