Rich_F
Rich_F

Reputation: 2056

Ruby count integers in array

Is there a way I can count the number of integers in an array? I have an array whose members come from a-z and 0-9. I want to count the number of integers in said array. I tried:

myarray.count(/\d/)

...but the count method doesn't regex.

a = 'abcdefghijklmnopqrstuvwxyz'.split('')
a << [0,1,2,3,4,5,6,7,8,9]
t = a.sample(10)
p t.count(/\d/)  # show me how many integers in here

Upvotes: 0

Views: 1197

Answers (1)

Zoran
Zoran

Reputation: 4226

The following should return the number of integers present within the array:

['a', 'b', 'c', 1, 2, 3].count { |e| e.is_a? Integer }
# => 3

Since #count can accept a block, we have it check if an element is an Integer, if so it will be counted towards our returned total.

Hope this helps!

Upvotes: 4

Related Questions