简体   繁体   中英

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 az 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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM