Ruby | Array count() operation
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
# Ruby code for count() method# to count elements # declaring arraya = [18, 22, 33, nil, 5, 6] # declaring arrayb = [1, 4, 1, 1, 88, 9] # declaring arrayc = [18, 22, nil, nil, 50, 6] # counting total elementsputs "counting : #{a.count}\n\n" # counting 1puts "counting : #{b.count(1)}\n\n" # counting 'nil'puts "counting : #{c.count(nil)}\n\n" |
Output :
counting : 6 counting : 3 counting : 2
Code #2 : Example for count() method
# Ruby code for count() method# to count elements # declaring arraya = ["abc", "nil", "dog"] # declaring arrayb = ["cow", nil, "dog"] # declaring arrayc = ["cat", nil, nil] # counting total elementsputs "counting : #{a.count}\n\n" # counting 1puts "counting : #{b.count(1)}\n\n" # counting 'nil'puts "counting : #{c.count(nil)}\n\n" |
Output :
counting: 3 counting : 0 counting : 2


