Ruby provides us three methods to interact with Array, Hashes or Objects.
Lets takes a simple array to explain the difference between these methods
array1 = [A, B, C, D, E]
array1.length
array1.size
array1.count
The output of the above three methods is same ie 5. So, this means that all these three methods basically return the number of elements present in an array.
The basic functionality of all the three methods remains same and only the count method have different variations.
Suppose array2 = [A, A, A, B, C, C, D, D, D, D, D, E]
If we give count method without any argument or condition then this method returns the number of elements present in an array
array2.count
This will return 12
If we have count the occurrence of any element in an array then we will pass that element as an argument with the count method.
array2.count 'A'
This will return the output as 3 because the occurrence of A in the array is three times.
If we want some elements on the basis of some condition in an array then we will use count method with the condition.
array3 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
array3.count{|a| < 4}
Output will be three because there are only three elements that are less than 4 in the given array.
0 Comment(s)