0

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
1
  • count(obj) uses == to count the number of elements equal to obj. So unless you're counting an array of regular expressions your code won't work. Moreover if it did work it still wouldn't count the integers because regex is used with strings. Commented May 9, 2018 at 18:15

1 Answer 1

4

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!

Sign up to request clarification or add additional context in comments.

1 Comment

Shorter version: ['a', 'b', 'c', 1, 2, 3].grep(Integer).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.