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):
-
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
-
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
Hope you found this post useful. It was published (and was last revised ). Please show your love and support by sharing this post.