Ruby | Array count() operation
Last Updated :
08 Jan, 2020
Array#count() : count() is a Array class method which returns the number of elements in the array. It can also find the total number of a particular element in the array.
Syntax: Array.count()
Parameter: obj - specific element to found
Return: removes all the nil values from the array.
Code #1 : Example for count() method
a = [ 18 , 22 , 33 , nil , 5 , 6 ]
b = [ 1 , 4 , 1 , 1 , 88 , 9 ]
c = [ 18 , 22 , nil , nil , 50 , 6 ]
puts "counting : #{a.count}\n\n"
puts "counting : #{b.count(1)}\n\n"
puts "counting : #{c.count(nil)}\n\n"
|
Output :
counting : 6
counting : 3
counting : 2
Code #2 : Example for count() method
a = [ "abc" , "nil" , "dog" ]
b = [ "cow" , nil , "dog" ]
c = [ "cat" , nil , nil ]
puts "counting : #{a.count}\n\n"
puts "counting : #{b.count(1)}\n\n"
puts "counting : #{c.count(nil)}\n\n"
|
Output :
counting: 3
counting : 0
counting : 2
Share your thoughts in the comments
Please Login to comment...