When to Use the Ruby Array#count Method?

Depending on the arguments passed to the Ruby Array#count method, it can be used in the following cases:

  1. Counting Total Items;
  2. Counting Specific Values;
  3. Conditional Counting.

Please note that Array#count is different from Array#size and Array#length methods, which are specifically used for getting the length of an array.

Counting Total Items

When used without arguments, it counts the total number of items in an array:

puts [3, 3, 4, 3, 3, 5, 5].count #=> 7
puts [].count #=> 0

Counting Specific Values

When used with a numeric argument, it counts the number of times the specific value occurs in an array:

puts [3, 3, 4, 3, 3, 5, 5].count(3) #=> 4
puts [].count(3) #=> 0

Conditional Counting

When used with a block, it counts the total number of items in an array that satisfy a condition based on the block:

puts [3, 3, 4, 3, 3, 5, 5].count { | item | item < 4 } #=> 4
puts [].count { | item | item < 4 } #=> 0

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.